Understanding thenCombine: Combining Independent Futures
You'll learn how to use thenCombine to merge results from two CompletableFutures that run independently in parallel.
The Core Idea
Unlike thenCompose which chains dependent async operations sequentially, thenCombine runs two CompletableFutures in parallel and combines their results when both complete. Think of it like ordering food from two different restaurants simultaneously—you wait for both deliveries, then combine them into one meal.
How thenCombine Works
thenCombine takes two parameters:
- Another
CompletableFuture<U>to run independently - A
BiFunction<T, U, V>that merges both results
CompletableFuture<Integer> future1 = supplyAsync(() -> {
// Simulate expensive computation
return 10;
});
CompletableFuture<String> future2 = supplyAsync(() -> {
// Independent computation
return "Result";
});
CompletableFuture<String> combined = future1.thenCombine(
future2,
(num, str) -> str + ": " + num
);
combined.join(); // "Result: 10"
Both future1 and future2 execute simultaneously, potentially on different threads. When both finish, the BiFunction receives both results and produces a combined value.
Key Characteristics
- Parallel execution: Both futures start immediately and run independently
- Wait for both: The combined future completes only when both inputs complete
- Type-safe merging: You can combine different result types (Integer + String → String)
- Exception handling: If either future fails, the combined future fails
Real-World Example
CompletableFuture<Double> priceCheck = supplyAsync(() -> fetchProductPrice());
CompletableFuture<Integer> stockCheck = supplyAsync(() -> fetchStockLevel());
CompletableFuture<String> availability = priceCheck.thenCombine(
stockCheck,
(price, stock) -> "Price: $" + price + ", Stock: " + stock
);
Key Takeaway: Use thenCombine when you have two independent async operations that can run in parallel, and you need both results to produce a final outcome—it maximizes throughput by avoiding unnecessary sequential waiting.