java - 如何链接多个 CompletableFuture
问题描述
我是 Java 的新手,正在使用 Springboot POSTING 来休息端点。我有一个使用 CompletableFuture 的场景,想知道如何链接多个期货。我也不需要将任何结果传递给期货。
场景 => Future f1 成功,然后 Future f2。如果 (f1 和 f2 ) 成功则 Future f3 ; (f1 或 f2 )失败然后 f3
我目前正在使用 supplyAsync,这是正确的方法吗?
CompletableFuture<String> f1 = CompletableFuture.supplyAsync( () -> postToEndpointA(a) ).thenCompose( () -> postToEnpointB(b))
我现在应该如何链接 f3?
解决方案
CompletableFuture
s 可以链接以处理成功的运行和失败的运行。
支持您的用例的结构之一如下所示:
public class Test {
public static void main(String[] args) throws JsonProcessingException, InterruptedException {
CompletableFuture.runAsync(() -> f1(false)) // f1 takes a bool val to switch success and fail runs
// f2 will run only if f1 completed successfully
.thenRun(Test::f2)
// throwable can be examined to check if there was any exception
// at previous stages. If throwable == null, there was no error
.whenComplete((unused, throwable) -> {
handleError(throwable);
f3();
});
// Wait for the thread above to complete
ForkJoinPool.commonPool().awaitTermination(4, TimeUnit.SECONDS);
}
private static void f1(boolean shouldFail) {
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));
if (shouldFail)
throw new RuntimeException("F1: Failed..");
System.out.println("f1: Completed.. ");
}
private static void f2() {
System.out.println("f2: Started...");
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
System.out.println("f2: Completed..");
}
private static void f3() {
System.out.println("f3: Runs irrespective of f1 and f2 result");
}
private static void handleError(Throwable throwable) {
if (throwable != null)
System.out.println(throwable.getMessage());
}
}
输出
shouldFail: false
f1: Completed..
f2: Started...
f2: Completed..
f3: Runs irrespective of f1 and f2 result
shouldFail: true
java.lang.RuntimeException: F1: Failed..
f3: Runs irrespective of f1 and f2 result
推荐阅读
- python - Odoo 12 中没有名为 Slugify 的模块
- javascript - 如何安装不在 package.json 中的 npm 依赖项?
- php - 在 lavarel 中使用刀片模板时,我无法加载 .js 文件和 .css
- jboss7.x - 如何将 jboss 配置为在 rhel 7 中作为服务运行
- java - 非空约束失败
- sockets - 套接字如何确定请求机器
- gmail - 如何修复 G1ANT imap 不检索任何电子邮件?
- git - 如何自动从 Azure DevOps 中的 master 分支
- javascript - 使用 React Dom 创建具有 id 或类的元素
- java - 由于接收超时和任务执行器失调导致的内存泄漏