@Async with CompletableFuture

In the previous section, we saw how we can use java.util.Future to get the result of asynchronous method execution. 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. But there are certain limitations to using the Future API:

  • Suppose we have written code to fetch the latest product price from an e-commerce system through a remote API. This task is time-consuming, so we need to run it asynchronously and use Future to get the result of that task. Now, the problem will occur when the remote API service is down. At that time, we need to complete Future manually by the last cached price of the product and that is not possible with Future.
  • Future only provides a get() method that notifies us when a result is available. We cannot attach a callback function to Future and have it get called automatically when the Future result is available.
  • Sometimes we have requirements, such as the result of the long-running task is needed to send another long-running task. We can't create such asynchronous workflow with Future.
  • We cannot run multiple Future in parallel.
  • The Future API does not have any exception handling.

Because of these limitations, Java 8 introduced a better abstraction than java.util.Future, called CompletableFuture. We can create CompletableFuture simply using the following no-arg constructor:

CompletableFuture<String> completableFuture = new CompletableFuture<String>();

Here is the list of methods provided by CompletableFuture, which help us to resolve the limitations of Future:

  • The complete() method is used to complete the task manually.
  • The runAsync() method is used to run background tasks asynchronously that do not return anything. It takes a Runnable object and returns CompletableFuture<Void>.
  • The supplyAsync() method is used to run background tasks asynchronously and return a value. It takes Supplier<T> and returns CompletableFuture<T>, where T is the type of the value given by the supplier.
  • The thenApply(), thenAccept(), and thenRun() methods are used to attach a callback to CompletableFuture.
  • The thenCompose() method is used to combine two dependent CompletableFuture together.
  • The thenCombine() method is used to combine two independent CompletableFuture together.
  • The allOf() and anyOf() methods are used to combine multiple CompletableFuture together.
  • The exceptionally() method is used to get the generated error from Future. We can log the error and set a default value.
  • The handle() method is used to handle the exception.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset