Combining via thenCombine()

While thenCompose() is useful to chain two dependent CompletableFuture instances, thenCombine() is useful to chain two independent instances of CompletableFuture. When both CompletableFuture instances complete we can continue .

Let's assume that we have the following two CompletableFuture instances:

private static CompletableFuture<Integer> computeTotal(String order) {

return CompletableFuture.supplyAsync(() -> {
return order.length() + new Random().nextInt(1000);
});
}

private static CompletableFuture<String> packProducts(String order) {

return CompletableFuture.supplyAsync(() -> {
return "Order: " + order
+ " | Product 1, Product 2, Product 3, ... ";
});
}

In order to deliver a customer order, we need to compute the total (for emitting the invoice) and pack the ordered products. These two actions can be accomplished in parallel. In the end, we deliver the parcel containing the ordered products and the invoice. Achieving this via thenCombine() can be done as follows:

CompletableFuture<String> cfParcel = computeTotal(order)
.thenCombine(packProducts(order), (total, products) -> {
return "Parcel-[" + products + " Invoice: $" + total + "]";
});

String parcel = cfParcel.get();

// e.g. Delivering: Parcel-[Order: #332 | Product 1, Product 2,
// Product 3, ... Invoice: $314]
logger.info(() -> "Delivering: " + parcel);

The callback function given to thenCombine() will be invoked after both CompletableFuture instances are complete.

If all we need is to do something when two CompletableFuture instances complete normally (this and another one) then we can rely on thenAcceptBoth(). This method returns a new CompletableFuture that is executed with the two results as arguments to the supplied action. The two results are this and the other given stage (they must complete normally). Here is an example:

CompletableFuture<Void> voidResult = CompletableFuture
.supplyAsync(() -> "Pick")
.thenAcceptBoth(CompletableFuture.supplyAsync(() -> " me"),
(pick, me) -> System.out.println(pick + me));

If the results of these two CompletableFuture instances are not needed, then runAfterBoth() is much preferred.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset