00:00

CompletableFuture in Java: Asynchronous Programming Made Practical

Last updated:

CompletableFuture is Java's main tool for asynchronous programming. It is a Future you can complete yourself, and a CompletionStage you can chain with callbacks, so you can describe a whole flow of async work without blocking threads.

This tutorial covers creating futures, combining many of them, completing them manually from callback-based code, and adding timeouts.

1. What Is CompletableFuture?

It is a class in java.util.concurrent, added in Java 8, that implements both Future<T> and CompletionStage<T>.

A CompletableFuture is completed either by an asynchronous task started with supplyAsync() or runAsync(), or explicitly by your code calling complete() or completeExceptionally(). Only the first completion counts.

2. CompletableFuture Hierarchy

CompletableFuture class hierarchyCompletableFuture implements Future and CompletionStage.«interface»Future<T>get(), cancel(…)isDone(), state()«interface»CompletionStage<T>thenApply(…), thenCompose(…)exceptionally(…), handle(…)«class»CompletableFuture<T>this pagesupplyAsync(…), runAsync(…) «static»allOf(…), anyOf(…) «static»complete(T), completeExceptionally(…)join(), getNow(T)orTimeout(…), completeOnTimeout(…) †† added in Java 9implementsinterfaceclass

Swipe sideways to see the whole diagram.

  • Future (interface): Provides blocking access: get(), plus cancel() and state checks.
  • CompletionStage (interface): Provides the chaining methods that build non-blocking pipelines.

3. Method Details

MethodDescription
supplyAsync(supplier, executor)Runs the supplier asynchronously and completes with its result.
runAsync(runnable, executor)Runs an action asynchronously; completes with null.
allOf(cfs…)Completes when all given futures complete.
anyOf(cfs…)Completes when any one of them completes, with that result.
complete(v), completeExceptionally(ex)Complete the future manually, if it is not already complete.
join(), getNow(fallback)Wait without checked exceptions, or read immediately with a fallback.
orTimeout(t, unit)Java 9+: completes exceptionally with TimeoutException if not done in time.
completeOnTimeout(v, t, unit)Java 9+: completes with a default value if not done in time.

4. Example: Finding the Cheapest Offer

A price-comparison feature asks three bookshops for a price in parallel. One shop is too slow, so it gets a placeholder after 400 ms.

CheapestBookPrice.java
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class CheapestBookPrice {

    record Offer(String shop, double price) {}

    static Offer ask(String shop, double price, long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return new Offer(shop, price);
    }

    public static void main(String[] args) {
        try (ExecutorService io = Executors.newFixedThreadPool(3)) {
            List<CompletableFuture<Offer>> offers = List.of(
                    CompletableFuture.supplyAsync(() -> ask("PageTurner", 34.90, 100), io),
                    CompletableFuture.supplyAsync(() -> ask("InkHouse", 31.50, 200), io),
                    CompletableFuture.supplyAsync(() -> ask("SlowBooks", 29.99, 3_000), io)
                            // Java 9+: give up after 400 ms and use a placeholder instead
                            .completeOnTimeout(new Offer("SlowBooks", Double.MAX_VALUE), 400, TimeUnit.MILLISECONDS));

            // allOf completes when every offer is in (or has timed out)
            CompletableFuture.allOf(offers.toArray(new CompletableFuture<?>[0])).join();

            Offer best = null;
            for (CompletableFuture<Offer> f : offers) {
                Offer o = f.join();                       // already complete, does not block
                System.out.println(o.shop() + ": "
                        + (o.price() == Double.MAX_VALUE ? "no answer in time" : o.price()));
                if (best == null || o.price() < best.price()) {
                    best = o;
                }
            }
            System.out.println("Cheapest: " + best.shop() + " at " + best.price());
        }
    }
}
Output
PageTurner: 34.9
InkHouse: 31.5
SlowBooks: no answer in time
Cheapest: InkHouse at 31.5

How the code works

  1. Each supplyAsync(…, io) call runs on the dedicated io executor rather than the shared common pool.
  2. completeOnTimeout() completes the slow shop's future with a placeholder after 400 ms; the slow task itself keeps running in the background.
  3. allOf() returns a CompletableFuture<Void> that completes when all three are done, and join() waits for it.
  4. After that every join() returns immediately, and a simple loop picks the lowest price.

5. Example: Wrapping a Callback-Based API

Many older libraries report results through callbacks. Creating a CompletableFuture with new and completing it from those callbacks turns them into a modern, composable API.

CallbackBridge.java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

public class CallbackBridge {

    // A legacy API that reports results through callbacks on its own thread
    static void verifyAddress(String postcode, Consumer<String> onSuccess, Consumer<Exception> onError) {
        new Thread(() -> {
            if (postcode.matches("\\d{5}")) {
                onSuccess.accept(postcode + " is deliverable");
            } else if (!postcode.equals("HANG")) {
                onError.accept(new IllegalArgumentException("invalid postcode " + postcode));
            }
            // "HANG" simulates a call that never answers
        }).start();
    }

    // Wrap the callback API in a CompletableFuture that we complete ourselves
    static CompletableFuture<String> verify(String postcode) {
        CompletableFuture<String> result = new CompletableFuture<>();
        verifyAddress(postcode, result::complete, result::completeExceptionally);
        return result.orTimeout(300, TimeUnit.MILLISECONDS);     // Java 9+: fail if no answer
    }

    public static void main(String[] args) {
        for (String postcode : new String[] {"10115", "X1", "HANG"}) {
            try {
                System.out.println("OK    " + verify(postcode).join());
            } catch (CompletionException e) {
                System.out.println("ERROR " + postcode + ": " + e.getCause().getClass().getSimpleName());
            }
        }
    }
}
Output
OK    10115 is deliverable
ERROR X1: IllegalArgumentException
ERROR HANG: TimeoutException

How the code works

  1. verify() creates an incomplete CompletableFuture and passes result::complete and result::completeExceptionally as the callbacks.
  2. orTimeout(300, MILLISECONDS) fails the future if no callback arrives in time.
  3. join() returns the value, or throws an unchecked CompletionException whose cause is the real error: IllegalArgumentException for the bad postcode, TimeoutException for the call that never answers.

6. Common Mistakes and Best Practices

  • Blocking I/O on the common pool. Async methods without an executor use ForkJoinPool.commonPool(); pass your own executor for blocking calls.
  • Calling get() or join() everywhere. Chain with thenApply() and friends, and block only at the edge of the application.
  • Expecting cancel(true) to interrupt. On a CompletableFuture it completes the future with a CancellationException but does not interrupt the task computing it.
  • Forgetting error handling. Add exceptionally() or handle(); otherwise failures surface only when someone joins.
  • Unbounded waits. Use orTimeout() or completeOnTimeout() for anything that talks to another system.

7. Summary

  • CompletableFuture implements Future and CompletionStage.
  • Start work with supplyAsync() / runAsync(), preferably on your own executor.
  • Combine results with allOf() and anyOf(); complete manually with complete().
  • Java 9 added orTimeout() and completeOnTimeout().
  • join() wraps failures in CompletionException; check getCause().

Related Tutorials

8. References