Differences between CompletableFuture and Future in Java 9?

JavaObject Oriented ProgrammingProgramming

CompletableFuture<T> class implements Future<T> interface in Java. CompletableFuture can be used as a Future that has explicitly completed. The Future interface doesn’t provide a lot of features, we need to get the result of asynchronous computation using the get() method, which is blocked, so there is no scope to run multiple dependent tasks in a non-blocking fashion whereas CompleteFuture class can provide the functionality to chain multiple dependent tasks that run asynchronously, so we can create a chain of tasks where the next task is triggered when the result of the current task is available.

Syntax

public class CompletableFuture<T> extends Object implements Future<T>, CompletionStage<T>

Example

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

public class CompletableFutureTest {
   public static void main(String args[]) throws ExecutionException, InterruptedException {
      Calculator calc = new Calculator(4, 7);
      CompletableFuture<Integer> future = CompletableFuture.supplyAsync(calc);
      future.thenAccept(result -> {
         System.out.println(result);
      });
      System.out.println("CompletableFutureTest End.... ");
      Thread.sleep(10000);
   }
}

// Calculator class
class Calculator implements Supplier<Integer> {
   private int x, y;
   public Calculator(int x, int y) {
      this.x = x;
      this.y = y;
   }
   @Override
   public Integer get() {
      try {
         Thread.sleep(3000);
      } catch(InterruptedException e) {
         e.printStackTrace();
      }
      return x + y;
   }
}

Output

CompletableFutureTest End....
11
raja
Published on 01-May-2020 15:15:14
Advertisements