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.

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
...the last 150 posts
...the last 10 comments
License