CompletableFuture with Spring Async
The CompletableFuture
class was introduced in Java 8, and it provides a simple way to write asynchronous, multithreaded, non-blocking code. With Spring MVC, it is also possible to use CompletableFuture
with controllers, services, and repositories from public methods annotated with @Async
. CompletableFuture
implements the Future
interface, which provides the result of an asynchronous computation.
We can create CompletableFuture
in the following simple way:
CompletableFuture<String> completableFuture = new CompletableFuture<String>();
To get the result of this CompletableFuture
, we can call the CompletableFuture.get()
method. This method will be blocked until Future
is completed. For that, we can manually call the CompletableFuture.complete()
method to complete
Future
:
completableFuture.complete("Future is completed")
runAsync() – running a task asynchronously
When we want to execute a background activity task asynchronously and do not want to return...