Java短路CompletableFuture

标签 java multithreading completable-future

我正在尝试找到一种根据特定条件跳过 CompletableFuture 的方法。

例如

public CompletableFuture<Void> delete(Long id) {
    CompletableFuture<T> preFetchCf = get(id);
    CompletableFuture<Boolean> cf1 = execute();

    /*This is where I want different execution path, if result of this future is true go further, else do not*/

    // Execute this only if result of cf1 is true
    CompletableFuture<T> deleteCf = _delete(id);
    // Execute this only if result of cf1 is true
    CompletableFuture<T> postDeleteProcess = postDelete(id);
}

实现这一目标的好方法是什么?

最佳答案

我将准备一个与您在问题中使用的示例不同的示例,因为从读者的角度来看,您的代码的意图并不十分清楚。

首先假设存在 CompletableFuture<String>提供星球大战角色的名称。

CompletableFuture<String> character = CompletableFuture.completedFuture("Luke");

现在,假设我还有另外两个 CompletableFuture代表我可能想要遵循的不同路径,具体取决于第一个可完成的 future 是否提供了绝地武士角色。

Supplier<CompletableFuture<String>> thunk1 = () -> CompletableFuture.completedFuture("This guy is a Jedi");
Supplier<CompletableFuture<String>> thunk2 = () -> CompletableFuture.completedFuture("This guy is not a Jedi");

请注意,我包装了 CompletableFuture在一个Supplier ,以避免它们被急切地评估(这是称为 thunk 的概念)。

现在,我转到我的异步链:

character.thenApply(c -> isJedi(c))
            .thenCompose(isJedi -> isJedi ? thunk1.get() : thunk2.get())
            .whenComplete((answer, error) -> System.out.println(answer));

使用thenCompose让我根据 boolean 结果选择一条路径。在那里,我评估了其中一个 thunk 并使其创建一个新的 CompletableFuture为了我在乎的路。

这将打印到屏幕上 "This guys is a Jedi" .

所以,我相信您正在寻找的是 thenCompose方法。

关于Java短路CompletableFuture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48588002/

相关文章:

java - 生成器设计模式: Required attributes

java - OpenFire 服务器中用户的 JID 应该是什么?

java - 了解 akka 中的调度程序

java - 一个java应用程序可以有多少个线程池

java - 如何在给定文件夹名称的情况下创建多个目录

multithreading - Perl 解释器线程的替代方案是什么?

java - 在 java 中,我如何处理 CompletableFutures 并获得第一个完成的理想结果?

java - 如何在 Spring Boot 中缓存 CompletableFuture 的值

java - 从 completablefuture 中检索 runnable 实例

c++ - 提高 C++ 的性能