# 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.
