Writing an Asynchronous Controller
Writing a controller and having it handle the request asynchronously is as simple as changing the return type of the controllers handler method . Let’s imagine that the call to HelloWorldController.hello takes quite some time but we don’t want to block the server for that.
The hello method now returns a Callable<String> instead of returning a String directly. Inside the newly constructed Callable<String> there is a random wait to simulate a delay before the message is returned to the client
Change the signature of the method to return CompletableFuture<String> and use the TaskExecutor to asynchronously execute the code.
Calling the supplyAsync (or when using void, use runAsync) a task is submitted.It returns a CompletableFuture. Here you use the supplyAsync method that takes both a Supplier and an Executor. This way you can reuse the TaskExecutor for async processing. If you use the supplyAsync method, which only takes a Supplier, it will be executed using the default fork/join pool available on the JVM.
When returning a CompletableFuture, you can take advantage of all the features of it like composing and chaining multiple CompletableFuture instances.