Home  >  Forum  >  Core Java
Post New Query

Java CompletableFuture vs Future



Asked on August 25, 2018
What is difference between Java CompletableFuture and Future?


Replied on August 28, 2018
1. Future is introduced in Java 5 and CompletableFuture is introduced in Java 8. CompletableFuture implements Future as well as CompletionStage.

2. Future is used for asynchronous computation. It provides (a) methods to check if computation is complete, (b) method to wait to complete the computation and (c) method to get result.

3. CompletableFuture is the extension of Java Future.   The result of CompletableFuture can be used as as CompletionStage for next computation and so on.

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

5. CompletionStage provides non-async and async methods both such as thenApply() and thenApplyAsync() . 

6. CompletableFuture has no direct control over the computation that causes it to be completed. Hence CompletableFuture cancellation is treated as exceptional completion. 

7. Future cancel() method attempts to cancel the execution of task and CompletableFuture cancel() method performs exceptional completion and do same as completeExceptionally() method of CompletableFuture.

8. Future runs using Executor and CompletableFuture can run either by using ForkJoinPool.commonPool() or Executor.

9.  Example of Java CompletableFuture

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

Output:

getDataById: ForkJoinPool.commonPool-worker-1
sendData: ForkJoinPool.commonPool-worker-1
Data:10 

10.  Example of Java Future

public class JavaFutureDemo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService exService = Executors.newSingleThreadExecutor();
Callable<String> task = new DemoTask();
Future<String> future = exService.submit(task);
//checks if cancelled
System.out.println("Is task cancelled:"+future.isCancelled());
//checks if task done
System.out.println("Is task done:"+future.isDone());
//waits to complete and fetches the value.
String s = future.get();
System.out.println(s);
exService.shutdown();
}
}
class DemoTask implements Callable<String>{
public String call() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println(e);
}
return "Task Done";
}
}

Output:

Is task cancelled:false
Is task done:false
Task Done




Write Answer








©2019 concretepage.com | Privacy Policy | Contact Us