Home > Blockchain >  How to chain multiple CompletableFuture
How to chain multiple CompletableFuture

Time:11-06

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?

CodePudding user response:

CompletableFutures 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

CodePudding user response:

CompletableFutures can be chained by calling thenRun to a run a task independent of the result or thenAccept which takes the initial result of say a call to supplyAsync and calls a function which you pass into the thenAccept method

  • Related