简体   繁体   中英

How to chain multiple CompletableFuture

I am newbie to Java and working on Springboot POSTING to rest endpoint. I have a scenario using CompletableFuture and would like to know how to chain multiple futures. I also don't need any result to be passed to the the futures.

Scenario => Future f1 successful, then Future f2. If (f1 and f2 ) are success then Future f3 ; (f1 or f2 ) fails then f3

I am currently using supplyAsync, is this the right approach?

CompletableFuture<String> f1 = CompletableFuture.supplyAsync( () -> postToEndpointA(a) ).thenCompose( () -> postToEnpointB(b)) 

How should i now chain f3?

CompletableFutures 可以通过调用thenRun来链接一个独立于结果的任务,或者thenAccept接受初始结果,比如调用supplyAsync并调用你传递给thenAccept方法的函数

CompletableFuture s can be chained to handle successful runs as well as failed runs.

One of the constructs to support your use-case looks like:

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());
    }
}   

Output

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM