DEV Community


Java 8 Multiple CompletableFutures

loizenai profile image loizenai ・2 min read

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>() {
        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:

Java 8 Multiple CompletableFutures

Discussion (0)

Editor guide