runAsync() – running a task asynchronously

When we want to execute a background activity task asynchronously and do not want to return anything from that task, we can use the CompletableFuture.runAsync() method. It takes a parameter as a Runnable object and returns the CompletableFuture<Void> type.

Let's try to use the runAsync() method by creating another controller method in our BankController class, with the following example:

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

CompletableFuture<String> completableFuture = new
CompletableFuture<>();
CompletableFuture.runAsync(new Runnable() {

@Override
public void run() {
try {
completableFuture.complete(syncService.syncCustomerAccount()
.get());
} catch (InterruptedException | ExecutionException e) {
completableFuture.completeExceptionally(e);
}

}
});
LOGGER.info("Leaving from controller");
return completableFuture;
}

In the preceding example, when a request comes with the /synccust path, it will run syncCustomerAccount() in a separate thread and will complete the task without returning any value.

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

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