首页 > 解决方案 > 如何链接多个 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?

标签: javaspring-bootcompletable-future

解决方案


CompletableFutures 可以链接以处理成功的运行和失败的运行。

支持您的用例的结构之一如下所示:

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

推荐阅读