Mastery
Mastery/Java/E. Concurrency
T2 · intermediate depth

CompletableFuture chaining: thenApply/thenCompose/thenCombine, sync vs. async

thenApply transforms a result. thenCompose chains to another async operation (like flatMap for futures -- use this, not thenApply, when your transform itself returns a CompletableFuture, or you'll end up with a future-of-a-future). thenCombine merges two independent futures. The ...Async variant of each guarantees execution on the common pool; the plain variant may run on the completing thread if the future is already done by the time you attach the callback.

java
import java.util.concurrent.*;

CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> 21).thenApply(x -> x * 2);
System.out.println("thenApply: " + f1.get());

CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(() -> 5)
    .thenCompose(x -> CompletableFuture.supplyAsync(() -> x * x));
System.out.println("thenCompose (chains to another future): " + f2.get());

CompletableFuture<Integer> a = CompletableFuture.supplyAsync(() -> 3);
CompletableFuture<Integer> b = CompletableFuture.supplyAsync(() -> 4);
System.out.println("thenCombine (merges two independent futures): " + a.thenCombine(b, (x, y) -> x + y).get());

The sync/async distinction, made visible by printing which thread each callback actually runs on:

java
String mainThreadName = Thread.currentThread().getName();
CompletableFuture<Void> chain = CompletableFuture.supplyAsync(() -> "value")
    .thenApply(v -> {
        System.out.println("  thenApply runs on: " + Thread.currentThread().getName());
        return v;
    })
    .thenApplyAsync(v -> {
        System.out.println("  thenApplyAsync runs on: " + Thread.currentThread().getName() + " (always a pool thread)");
        return v;
    })
    .thenAccept(v -> {});
chain.get();

exceptionally recovers from a failed future, without needing a try/catch around a blocking .get():

java
CompletableFuture<Integer> failing = CompletableFuture.<Integer>supplyAsync(() -> {
    throw new RuntimeException("computation failed");
}).exceptionally(ex -> {
    System.out.println("  recovered from: " + ex.getMessage());
    return -1;
});
System.out.println("recovered value: " + failing.get());

Interview angle

A strong practical question: "chain two independent async calls and combine their results — what method do you reach for?" (thenCombine), followed by "now make the second call depend on the first's result" (thenCompose, not thenApply) — mixing these two up (using thenApply when the transform itself returns a future) is one of the most common real mistakes, producing a CompletableFuture<CompletableFuture<T>> that candidates often don't immediately recognize as wrong.

In the industry

CompletableFuture chains are the standard way to compose async operations in Java before or alongside virtual threads — orchestrating calls to multiple downstream services, combining their results, and handling failures without blocking threads unnecessarily. The sync-vs-async (thenApply vs thenApplyAsync) distinction matters most when a callback does real work: forgetting the Async variant can accidentally run expensive logic on a thread you didn't intend to occupy (sometimes the calling thread, sometimes whichever pool thread happened to complete the previous stage).