Adam Bien's Weblog

Java 8 CompletableFuture Example

A result of an expensive task:


    UUID createId() {
        return UUID.randomUUID();
    }

needs to be passed to:


 void store(String message) {
        System.out.println("message = " + message);
    }

...and therefore converted with:


    String convert(UUID input) {
        return input.toString();
    }

CompletableFuture allows you to build pipeline executed asynchronously within the ForkJoinPool:

import static java.util.concurrent.CompletableFuture.supplyAsync;

   supplyAsync(this::createId).
                thenApply(this::convert).
                thenAccept(this::store);

...block and wait for the result:

   supplyAsync(this::createId).
               thenApply(this::convert).
               thenAccept(this::store).get();


...and even control the concurrency:


        ExecutorService es = Executors.newFixedThreadPool(2);
        supplyAsync(this::createId,es).


CompletableFuture is particularly useful in Java EE (checkout http://javaeemicro.services) and is often used together with ManagedExecutorService / https://github.com/AdamBien/porcupine.

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


NEW workshop: HTML 5 and JavaScript Essentials, Three days in April 2017: from Java EE 7 Architectures over Microservices to Performance, Troubleshooting and Monitoring
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

I don't understand why this would be useful? In the end both variants have to wait for the output, right?

So why would I want to add this complexity at all?

Posted by Bernd on October 19, 2016 at 08:33 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License