Showing posts with label completablefuture. Show all posts
Showing posts with label completablefuture. Show all posts

Friday, November 6, 2015

Using Java 8 CompletableFuture with Spring @Async annotated methods

Future interface was added in Java 5 but it had a major downside: you had to wait for it to return the result if you wanted to do something with it. Spring framework added SettableListenableFuture which allowed to register callbacks, but now Java 8 added CompletableFuture class and in release 4.2 Spring added support for it.


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.