[英]How to chain multiple 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?
CompletableFutures 可以通过调用thenRun
来链接一个独立于结果的任务,或者thenAccept
接受初始结果,比如调用supplyAsync
并调用你传递给thenAccept
方法的函数
CompletableFuture
可以链接起来处理成功的运行和失败的运行。
支持您的用例的结构之一如下所示:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.