Java Future vs CompletableFuture

Java Future vs CompletableFuture

CompletableFuture is an extension to Java’s Future API which was introduced in Java 5.

A Future is used as a reference to the result of an asynchronous computation. It provides an isDone() method to check whether the computation is done or not, and a get() method to retrieve the result of the computation when it is done.

The Future interface was added in Java 5 to serve as a result of an asynchronous computation, but it did not have any methods to combine these computations or handle possible errors.

Future API was a good step towards asynchronous programming in Java but it lacked some important and useful features

Limitations of Future

  1. It cannot be manually completed
    1. Let’s say that you’ve written a function to fetch the latest price of an e-commerce product from a remote API.
    2. Since this API call is time-consuming, you’re running it in a separate thread and returning a Future from your function.
    3. Now, let’s say that If the remote API service is down, then you want to complete the Future manually by the last cached price of the product.
    4. Can you do this with Future? No!
  2. You cannot perform further action on a Future’s result without blocking
    1. Future does not notify you of its completion. It provides a get() method which blocks until the result is available.
    2. You don’t have the ability to attach a callback function to the Future and have it get called automatically when the Future’s result is available.
  3. Multiple Futures cannot be chained together
    1. Sometimes you need to execute a long-running computation and when the computation is done, you need to send its result to another long-running computation, and so on.
    2. You can not create such asynchronous workflow with Futures.
  4. You can not combine multiple Futures together
    1. Let’s say that you have 10 different Futures that you want to run in parallel and then run some function after all of them completes. You can’t do this as well with Future.
  5. No Exception Handling
    1. Future API does not have any exception handling construct.
    2. CompletableFuture implements Future and CompletionStage interfaces and provides a huge set of convenience methods for creating, chaining and combining multiple Futures. It also has a very comprehensive exception handling support.

All of these limitations are addressed with CompletableFuture - which was introduced in Java8.