Attaching a callback that processes the result of an asynchronous task and returns void

User problem: Fetch the order of a certain customer and print it.

Typically, a callback that doesn't return a result acts as a terminal action of an asynchronous pipeline.

This behavior can be obtained via the thenAccept() method. It takes  Consumer<T> and returns CompletableFuture<Void>. This method can process and transform the result of CompletableFuture, but doesn't return a result. So, it can take an order, which is the result of  CompletableFuture, and print it as shown in the following snippet of code:

public static void fetchAndPrintOrder() {

CompletableFuture<String> cfFetchOrder
= CompletableFuture.supplyAsync(() -> {

logger.info(() -> "Fetch order by: "
+ Thread.currentThread().getName());
Thread.sleep(500);

return "Order #1024";
});

CompletableFuture<Void> cfPrintOrder = cfFetchOrder.thenAccept(
o -> logger.info(() -> "Printing order " + o +
" by: " + Thread.currentThread().getName()));

cfPrintOrder.get();
logger.info("Order was fetched and printed ");
}

Or, it can be more compact as follows:

public static void fetchAndPrintOrder() {

CompletableFuture<Void> cfFetchAndPrintOrder
= CompletableFuture.supplyAsync(() -> {

logger.info(() -> "Fetch order by: "
+ Thread.currentThread().getName());
Thread.sleep(500);

return "Order #1024";
}).thenAccept(
o -> logger.info(() -> "Printing order " + o + " by: "
+ Thread.currentThread().getName()));

cfFetchAndPrintOrder.get();
logger.info("Order was fetched and printed ");
}
Check also acceptEither() and acceptEitherAsync().
..................Content has been hidden....................

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