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
- First operation returns
CompletableFuture<A> .thenCompose(a -> ...)usesato createCompletableFuture<B>.thenCompose(b -> ...)usesbto createCompletableFuture<C>- 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.