DEV Community

loizenai
loizenai

Posted on

Java 8 Multiple CompletableFutures

https://grokonez.com/java/java-8/java-8-multiple-completablefutures

Java 8 Multiple CompletableFutures

In previous posts, we have concept of how to use CompletableFutures. This tutorial is about combining multiple CompletableFutures, it is one of the most important and useful abilities of Java 8 asynchronous processing.

Related articles:

I. Usage

1. thenCompose()

<U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn)

thenCompose() can chain 2 CompletableFutures by using the result which is returned from the invoking future.

private static void testCompose() throws InterruptedException, ExecutionException {
    CompletableFuture<String> future = createCF(2); // inside future
    CompletableFuture<String> combinedFuture = future.thenCompose(MainApp::calculateCF);

    combinedFuture.thenAccept(result -> System.out.println("accept: " + result));
    // check results
    System.out.println("Future result>> " + future.get());
    System.out.println("combinedFuture result>> " + combinedFuture.get());
}

private static CompletableFuture<String> calculateCF(String s) {

    return CompletableFuture.supplyAsync(new Supplier<String>() {
        @Override
        public String get() {
            System.out.println("> inside new Future");
            return "new Completable Future: " + s;
        }
    });
}

combinedFuture uses thenCompose() method of future with calculateCF function to get and modify the result from previous step of future.

Run the code, the Console shows:


inside future: waiting for detecting index: 2...
inside future: done...
> inside new Future
accept: new Completable Future: 2
Future result>> 2
combinedFuture result>> new Completable Future: 2

More at:

https://grokonez.com/java/java-8/java-8-multiple-completablefutures

Java 8 Multiple CompletableFutures

Top comments (0)