CompletableFuture allows to chain several asynchronous calls which takes asynchronous to another level. But the class is rather complex, it has more than 40 methods. How do we take advantage of it together with asynchronous support offered by Spring?
Lets say we are implementing a method which returns a String result:
public String getResult() {
return "result";
}
Now we want to make this method asynchronous and return CompletableFuture. Let's assume we already have all the necessary configurations for executing methods with @Async (i.e. we have @EnableAsync annotation in the configuration and defined TaskExecutor bean).
First, we'll add @Async annotation to the method and change the return type.
@Async
public CompletableFuture<String> getResult() {
return "result";
}
This will not even compile. But how do we convert string to CompletableFuture? We can use the static method completedFuture:
@Async
public CompletableFuture<String> getResult() {
return CompletableFuture.completedFuture("result");
}
We also need to process the result in the calling method. If we want to process both successes and failures we can execute whenComplete method:
getResult().whenComplete(...);
Now you've taken advantage of CompletableFuture.