Saturday, November 7, 2015

Cloudy with a chance of confusion

Cloud is very popular these day, one of the consequences is the number of terms and products which have the word Cloud in its name which causes a lot of confusion.
I'll try to collect here some of them.

  • CloudFormation - AWS Configuration management tool, which uses templates with a special format.
  • CloudStack - opensource software to manage VMs.
  • CloudFoundry - cloud computing PaaS, some of the cloud providers (e.g. IBM Bluemix) are based on it

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.