Course contentsShow
← Java
Lesson 2819 of 2,87051. CompletableFutureFree lesson

Chaining Multiple Async Operations with thenCompose

Chain three or more async operations in sequence, each using the previous result to start the next computation.

Chaining Multiple Async Operations with thenCompose

What You'll Learn

You'll learn how to chain three or more asynchronous operations in sequence, where each operation depends on the result of the previous one, creating a clean linear pipeline without nesting.

The Core Idea

When you have multiple async operations that must execute in order—each using the previous result—you use thenCompose repeatedly to create a flat, readable chain. Think of it like a relay race: runner A passes the baton to runner B, who passes it to runner C, and so on. Each runner (async operation) starts only when they receive the baton (previous result).

Without thenCompose, you'd end up with nested CompletableFuture<CompletableFuture<CompletableFuture<T>>>, which is messy and hard to work with. thenCompose flattens this into a single chain.

Three-Step Example

CompletableFuture<String> result = CompletableFuture.supplyAsync(() -> {
    return 5; // Step 1: Get initial value
})
.thenCompose(num -> CompletableFuture.supplyAsync(() -> {
    return num * 2; // Step 2: Double it asynchronously
}))
.thenCompose(doubled -> CompletableFuture.supplyAsync(() -> {
    return "Result: " + doubled; // Step 3: Format as string
}));

System.out.println(result.join()); // "Result: 10"

Each thenCompose receives the previous result, performs an async operation, and returns a new CompletableFuture. The chain remains flat and readable.

The Pattern

  1. First operation returns CompletableFuture<A>
  2. .thenCompose(a -> ...) uses a to create CompletableFuture<B>
  3. .thenCompose(b -> ...) uses b to create CompletableFuture<C>
  4. Continue as needed

Key Takeaway: Chain multiple dependent async operations using successive thenCompose calls to create a flat, sequential pipeline where each stage receives the previous result and spawns the next async computation.