Java CompletableFuture vs CompletionStage

Asked on August 27, 2018
What is difference between Java CompletableFuture vs CompletionStage?

Replied on August 27, 2018
1. CompletionStage is an interface and CompletableFuture is the implementation of the CompletionStage.  CompletableFuture also implements Future.

2. CompletableFuture is a Future that may be explicitly completed and may be used as CompletionStage to complete another action.

3. CompletionStage completes a given action on completion of another CompletionStage possibly asynchronously.  CompletionStage declares methods starting with accept, apply, handle, run, then and when.

4. CompletableFuture completes non-async methods (such as thenAccept(), thenApply()) using thread of either caller of current method or current CompletableFuture.

5. Look into the code.

public class SupplyAsyncExample1 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
CompletableFuture<String> cf = CompletableFuture.supplyAsync(()-> getDataById(10))
.thenApply(data -> sendData(data));
private static String getDataById(int id) {
System.out.println("getDataById: "+ Thread.currentThread().getName());
return "Data:"+ id;
private static String sendData(String data) {
System.out.println("sendData: "+ Thread.currentThread().getName());
return data;


getDataById: ForkJoinPool.commonPool-worker-1
sendData: main

Main thread starts executing the code and when it reaches to supplyAsync() then supplyAsync() takes new thread from ForkJoinPool.commonPool() to executes its function asynchronously.

Write Answer

©2024 | Privacy Policy | Contact Us