Tuesday, 15 August 2017

CompletableFuture Detail Discussion

CompletableFuture :-


For details description of CompletableFuture please visit below java docs.

Before starting CompletableFuture let’s revisit our Future interface blog :-

get() method of Future return the result of computation when computation done successfully. So it is clear the get() will block until computation is done, this behavior of get() makes the asynchronous call fruitless. Although we can put the logic but that will be an overhead.

To overcome this problem Java 8 introduces CompletableFuture.
CompletableFuture implements Future as well as CompletionStage interface. CompletionStage provide many callback method which executes on completion.

Let’s discuss with example:-

package com.test.main;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureTest {

private static Integer number;
public static void main(String[] args) throws InterruptedException,  ExecutionException {
       CompletableFutureTest completableFutureTest = new CompletableFutureTest();
       completableFutureTest.getNumberCount();
       }
 public Integer getNumberCount() throws InterruptedException, ExecutionException {
       CompletableFuture<Integer> futureCount =   CompletableFuture.supplyAsync(this::getNumber);
       return futureCount.get();
 }
 public Integer getNumber() {
       return number;
 }
}

In above code we are not providing any thread executor, here CompletableFuture will run the task in ForkJoinPool.commonPool() Or we can provide our own executor check below code snippet:-

public Integer getNumberCount() throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newFixedThreadPool(1);
CompletableFuture<Integer> futureCount = CompletableFuture.supplyAsync(this::getNumber, executorService);
       return futureCount.get();
}

CompletabeFuture provide two ways of asynchronous execution
1.      supplyAsync (return a value)
2.      runAsync(return void)

Above both methods support custom executor as well as ForkJoinPool.commonPool() for thread pool. Refer below code snippet:-

public Void getNumberCount() throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newFixedThreadPool(1);
CompletableFuture<Void> futureCount = CompletableFuture.runAsync(this::getNumber, executorService);
       return futureCount.get();

}

1 comment: