Concurrency Java
Aniket Kulkarni  

Java Future and CompletableFuture

Future and CompletableFuture are used in Java for Asynchronous processing of tasks. In this blog post, I am going to cover Java’s Future and CompletableFuture differences and their usage through an example. We will go through the important methods available in interface Future and class CompletableFuture. Let’s get started.

Interface Future

  • Introduced in Java 1.5
  • Package java.util.concurrent
  • Used for asynchronous computation
  • Most commonly used methods
    • get:- Waits until the computation is done and then receives the result
    • isDone:- Returns true if this task completed, terminated, cancelled or an exception occurred
  • Additionally, there is cancel method is available to cancel a task

I believe an example program makes picture clear. Now, let’s see how can we implement it.

Runnable

  • To execute a async task Runnable is first option that comes into mind.
  • This interface is there in Java since JDK 1.0.
  • Implement the public void run() method and provide an business logic.
  • There is no way to return the processed value or object back to caller. Since, run method returns void.

This is common example of using threads in Java. Wait, is there any way to return a value to the caller? Of course, yes. Implement callable interface

Callable

  • Introduced in Java 1.5.
  • Task returns a single value to the caller
  • Implement the public <V> call() method

In the above example, call method returns the String value. As interface Callable<String> is using String as type parameter. Now, it is possible to return an orderId as string parameter.

The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.

Class CompletableFuture

  • Introduced in Java 1.8
  • Package java.util.concurrent
  • Implements two interfaces CompletionStage<T>, Future<T>
  • All the methods from Future interface are available
  • Following are the methods, which makes the CompletableFuture class different from the Future class:

Using these methods you can chain the tasks. This means do the task A, when you are done, do this another task B using the result of task A. The main advantage of using CompletableFuture over Future is we can do the operations without blocking the thread to wait for a result.

Remember: There is no support for Callable when using CompletableFutrure. Only two methods available runAsync and supplyAsync.

To understand the concept better, I have created a sample application. Example demonstrates the use of CompletableFuture. Git Repository URL:- java-concurrency. More updates coming soon!!!