supplyAsync() – running a task asynchronously, with a return value

When we want to return a result after finishing a task asynchronously, we can use CompletableFuture.supplyAsync(). It takes Supplier<T> as a parameter and returns CompletableFuture<T>.

Let's check the supplyAsync() method by creating another controller method in our BankController class, with the following example:

@RequestMapping(value = "/synccustbal")
@ResponseBody
public CompletableFuture<String> syncCustomerBalance() {
LOGGER.info("Entering in controller");

CompletableFuture<String> completableFuture =
CompletableFuture.supplyAsync(new Supplier<String>() {

@Override
public String get() {
try {
return syncService.syncCustomerBalance().get();
} catch (InterruptedException | ExecutionException e) {
LOGGER.error(e);
}
return "No balance found";
}
});
LOGGER.info("Leaving from controller");
return completableFuture;
}

The CompletableFuture object uses the global thread pool, ForkJoinPool.commonPool(), to execute tasks in a separate thread. We can create a thread pool and pass it to runAsync() and supplyAsync() methods.

The following are two variants of the runAsync() and supplyAsync() methods:

CompletableFuture<Void> runAsync(Runnable runnable)
CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
CompletableFuture<U> supplyAsync(Supplier<U> supplier)
CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
..................Content has been hidden....................

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