Attaching a callback that runs after an asynchronous task and returns void

User problem: Deliver an order and notify the customer.

Notifying the customer should be accomplished after delivering the order. This is just an SMS of the Dear customer, your order has been delivered today type, so the notification task doesn't need to know anything about the order. These kinds of tasks can be accomplished by thenRun(). This method takes Runnable and returns CompletableFuture<Void>. Let's see it at work:

public static void deliverOrderNotifyCustomer() {

CompletableFuture<Void> cfDeliverOrder
= CompletableFuture.runAsync(() -> {

logger.info(() -> "Order was delivered by: "
+ Thread.currentThread().getName());
Thread.sleep(500);
});

CompletableFuture<Void> cfNotifyCustomer
= cfDeliverOrder.thenRun(() -> logger.info(
() -> "Dear customer, your order has been delivered today by:"
+ Thread.currentThread().getName()));

cfNotifyCustomer.get();
logger.info(() -> "Order was delivered
and customer was notified ");
}
For further parallelization, thenApply(), thenAccept(), and thenRun() are accompanied by thenApplyAsync(), thenAcceptAsync(), and thenRunAsync(). Each of these can rely on the global ForkJoinPool.commonPool() or a custom thread pool (Executor). While thenApply/Accept/Run() are executed in the same thread as the CompletableFuture task was executed before (or in the main thread), thenApplyAsync/AcceptAsync/RunAsync() may be executed in a different thread (from ForkJoinPool.commonPool() or a custom thread pool (Executor)).
..................Content has been hidden....................

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