Home  >  JDK 8

Java 8 CompletableFuture Example

By Arvind Rai, December 03, 2014
java.util.concurrent.CompletableFuture is a Future in java 8 which is the derived class of java.util.concurrent.CompletionStage. CompletableFuture can be completed setting value and status explicitly. There are different methods in CompletableFuture that can be used to handle task. Here in this page we will provide the example of some methods like supplyAsync, thenApply, join, thenAccept, whenComplete and getNow.

CompletableFuture.supplyAsync

supplyAsync accepts a Supplier as an argument and complete its job asynchronously. The result of supplier is run by a task from ForkJoinPool.commonPool() as default. We can also pass our Executor. Finally supplyAsync method returns CompletableFuture on which we can apply other methods.

CompletableFuture.thenApply

thenApply method accepts a function as an argument. Once the calling CompletableFuture completes , then on the result of this stage, that function is applied by thenApply method and returns a CompletableFuture.

CompletableFuture.join

join method returns the result after completion or throws CompletionException. This method waits for the completion of calling completion stage.
CompletableFutureOneExample.java
package com.concretepage.util.concurrent;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class CompletableFutureOneExample {
    public static void main(String[] args) throws InterruptedException {
        List<Integer> list = Arrays.asList(10,20,30,40);
        list.stream().map(data->CompletableFuture.supplyAsync(()->getNumber(data))).
                map(compFuture->compFuture.thenApply(n->n*n)).map(t->t.join())
                .forEach(s->System.out.println(s));
    }
    private static int getNumber(int a){
        return a*a;
    }
} 
Find the output.
10000
160000
810000
2560000 

CompletableFuture.thenAccept

thenAccept method accepts Consumer as an argument. On the completion of any completion stage, thenAccept method applies Consumer on the result and returns CompletableFuture.
CompletableFutureTwoExample.java
package com.concretepage.util.concurrent;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class CompletableFutureTwoExample {
    public static void main(String[] args) throws InterruptedException {
        List<String> list = Arrays.asList("A","B","C","D");
        list.stream().map(data->CompletableFuture.supplyAsync(()->"Processing:"+data)).
                map(compFuture->compFuture.thenAccept(s->System.out.println(s))).map(t->t.join())
                .count();
    }
} 
Find the output.
Processing:A
Processing:B
Processing:C
Processing:D 

CompletableFuture.whenComplete

whenComplete method uses BiConsumer as an argument. Once the calling completion stage completes, whenComplete method applies completion stage result on BiConsumer. BiConsumer takes first argument as result and second argument as error if any.
CompletableFutureThreeExample.java
package com.concretepage.util.concurrent;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class CompletableFutureThreeExample {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("A","B","C","D");
        list.stream().map(s->CompletableFuture.supplyAsync(()->s+s))
                .map(f->f.whenComplete((result,error)->System.out.println(result+" Error:"+error))).count();
    }
} 
Find the output.
AA Error:null
BB Error:null
CC Error:null
DD Error:null 

CompletableFuture.getNow

getNow is a method that if calling completion stage is not completed then the value passed to getNow will be set to result.
CompletableFutureFourExample.java
package com.concretepage.util.concurrent;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class CompletableFutureFourExample {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("A","B","C","D");
        list.stream().map(s->CompletableFuture.supplyAsync(()->s+s))
                .map(f->f.getNow("Not Done")).forEach(s->System.out.println(s));
    }
} 
The output of the above program will be random. At the time of calling getNow, if thread is completed, then that result is returned else the default value set by getNow will be returned.
Not Done
Not Done
CC
Not Done 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS
comments powered by Disqus








Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us