User problem: Fetch the order summary of a certain customer.
By default, as in the preceding examples, the asynchronous tasks are executed in threads obtained from the global ForkJoinPool.commonPool(). By simply logging Thread.currentThread().getName(), we see something as ForkJoinPool.commonPool-worker-3.
But we can also use an explicit Executor custom thread pool. All the CompletableFuture methods that are capable of running asynchronous tasks provide a flavor that takes Executor.
Here is an example of using a single thread pool:
public static void fetchOrderSummaryExecutor() {
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<String> cfOrderSummary
= CompletableFuture.supplyAsync(() -> {
logger.info(() -> "Fetch order summary by: "
+ Thread.currentThread().getName());
Thread.sleep(500);
return "Order Summary #91022";
}, executor);
// wait for summary to be available, this is blocking
String summary = cfOrderSummary.get();
logger.info(() -> "Order summary: " + summary + " ");
executor.shutdownNow();
}