Chaining Multiple thenCombine Operations
What you'll learn: How to combine more than two independent CompletableFuture instances by chaining multiple thenCombine calls together.
The Challenge of Combining Multiple Futures
You've learned how thenCombine merges two independent futures. But what if you need to combine three, four, or more asynchronous computations? The solution is to chain thenCombine operations sequentially, where each call combines the previous result with another future.
Sequential Chaining Pattern
Think of it like assembling a meal: first you combine the main course with a side dish, then you add the dessert, then the beverage. Each step builds on the previous combination.
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Data1");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Data2");
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "Data3");
CompletableFuture<String> combined = future1
.thenCombine(future2, (result1, result2) -> result1 + ", " + result2)
.thenCombine(future3, (combined12, result3) -> combined12 + ", " + result3);
String finalResult = combined.join(); // "Data1, Data2, Data3"
Understanding the Flow
- Step 1:
future1andfuture2run in parallel and combine their results - Step 2: The combined result is then merged with
future3's result - All three original futures execute concurrently from the start
Nested Pattern for Complex Combinations
For more control, you can nest thenCombine calls:
CompletableFuture<Integer> sum = future1
.thenCombine(future2, (a, b) -> a + b)
.thenCombine(
future3.thenCombine(future4, (c, d) -> c + d),
(ab, cd) -> ab + cd
);
This pattern lets you control how intermediate results combine before final aggregation.
Key Takeaway: Chain thenCombine operations to merge multiple independent futures, where each call combines the accumulated result with one more future—all original futures execute in parallel, maximizing concurrency.