Sub topic 6
Combining independent results with `thenCombine`
This chapter assumes Java 8 lambdas, generics, CompletableFuture, and basic ExecutorService use. The focus is combining two asynchronous operations that do not depend on each other.
When `thenCombine` fits
Suppose an application must load a product and its shipping cost. Neither operation needs the result of the other, so they can start at the same time. After both finish, the application can calculate the final price.
thenCombine combines two futures:
- The first future produces a value of type
T. - The second future produces a value of type
U. - A combining function receives both values and returns a value of type
V.
The resulting future completes when both input futures complete successfully.
import java.util.concurrent.CompletableFuture;
public class CombineDemo {
public static void main(String[] args) {
CompletableFuture<Double> productPrice =
CompletableFuture.supplyAsync(() -> {
sleep(300);
return 80.0;
});
CompletableFuture<Double> shippingCost =
CompletableFuture.supplyAsync(() -> {
sleep(500);
return 7.50;
});
CompletableFuture<Double> total =
productPrice.thenCombine(
shippingCost,
(price, shipping) -> price + shipping
);
System.out.println("Total: " + total.join());
}
private static void sleep(long milliseconds) {
try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted", e);
}
}
}Both calls to supplyAsync begin independently. The total future does not calculate its result when thenCombine is called. It calculates the result after productPrice and shippingCost have both completed.
The two input types and the output type do not have to be the same. For example, one future could produce a User, another could produce a List<Order>, and the combining function could return a UserSummary.
Understanding the timing
The futures run concurrently when their executor allows it. In the example, the total becomes available after the slower operation finishes, plus the small time needed for the combining function. It does not wait for the first operation and then start the second one.
thenCombine is different from thenCompose. Use thenCompose when the second asynchronous operation needs the first result. Use thenCombine when both operations can start without knowing each other's results.
| Situation | Suitable method |
|---|---|
| The second task needs the first task's value | `thenCompose` |
| Two tasks are independent and need one final result | `thenCombine` |
Completion and failure
Calling join() on the combined future waits for its result. In production code, avoid calling join() on an application thread that must remain responsive. Prefer returning the future to a caller that can continue the asynchronous workflow.
If either input future completes exceptionally, the combined future also completes exceptionally, and the combining function is not called.
For example, a shipping lookup can provide a default value before the combination:
CompletableFuture<Double> safeShipping =
shippingCost.exceptionally(error -> 0.0);
CompletableFuture<Double> total =
productPrice.thenCombine(
safeShipping,
(price, shipping) -> price + shipping
);This changes the policy from “fail if shipping lookup fails” to “use free shipping if lookup fails.” Choose that policy deliberately. A default can hide an outage when shipping information is required for correctness.
Exercise
Exercise
Two independent futures produce an item price and a tax amount. Which method combines them, and when does the combining function run?
Show answer
Use thenCombine. The combining function runs after both futures complete successfully.