Sep 27, 2013

CompletableFuture in Java 8

Fork/Join Application Programming with CompletableFuture in Java 8

Today at the JavaOne I saw a very inspiring session about reactive programming with Java 8. The idea is quite simple. Build a pipeline of later running actions (Futures) which can run asnchron and provide synchronisation mehtods to join (combine) or split parallel actions. It will us help to parallize our code to make a application more reactive and powerful.

Why we should do so is written here:

Look at some code:

final CompletableFuture<ArrayList<User>> users = 
        CompletableFuture.supplyAsync(() -> {
            //lookup all users ... this can run for a long time
            return new ArrayList<User>(Arrays.asList(new User("u1")));

final CompletableFuture<ArrayList<Product>> products = 
        CompletableFuture.supplyAsync(() -> {
            //lookup all products ...  this can run for a long time
            return new ArrayList<Product>(Arrays.asList(new Product("p1")));

 final CompletableFuture<String> report = users.thenCombine(products, (u, p) -> {
            return u.toString() + p.toString(); // demo here

 System.out.println(report.join()); -> "{u1}{p1}"

The clue lies in the supplyAsync factory method. It returns a Future which has as parameter the return value of the parallel executed action. Here in this example we want the lookup for products and users and then combine the results to a string. 
The searching for products and the searching for users runs parallel. This class is a very useful wrapper over the ForkJoinPool of JDK 7. You can set up easily parallel workflow pipelines. 
You can also use another executor to run in a JEE server (Glassfish 4 has concurrency APIs to execute things parallel). Look at the JSR 236.

See also:

No comments:

Post a Comment