Guide To CompletableFuture

I just announced the new Spring 5 modules in REST With Spring:

1. Introduction

This article is a guide to the functionality and use cases of the CompletableFuture class – introduced as a Java 8 Concurrency API improvement.

2. Asynchronous Computation in Java

Asynchronous computation is difficult to reason about. Usually we want to think of any computation as a series of steps. But in case of asynchronous computation, actions represented as callbacks tend to be either scattered across the code or deeply nested inside each other. Things get even worse when we need to handle errors that might occur during one of the steps.

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.

In Java 8, the CompletableFuture class was introduced. Along with the Future interface, it also implemented the CompletionStage interface. This interface defines the contract for an asynchronous computation step that can be combined with other steps.

CompletableFuture is at the same time a building block and a framework with about 50 different methods for composing, combining, executing asynchronous computation steps and handling errors.

Such a large API can be overwhelming, but these mostly fall in several clear and distinct use cases.

3. Using CompletableFuture as a Simple Future

First of all, the CompletableFuture class implements the Future interface, so you can use it as a Future implementation, but with additional completion logic.

For example, you can create an instance of this class with a no-arg constructor to represent some future result, hand it out to the consumers and complete it at some time in the future using the complete method. The consumers may use the get method to block the current thread until this result will be provided.

In the example below we have a method that creates a CompletableFuture instance, then spins off some computation in another thread and returns the Future immediately.

When the computation is done, the method completes the Future by providing the result to the complete method:

To spin off the computation, we use the Executor API which is described in the article “Introduction to Thread Pools in Java”, but this method of creating and completing a CompletableFuture can be used together with any concurrency mechanism or API including raw threads.

Notice that the calculateAsync method returns a Future instance.

We simply call the method, receive the Future instance and call the get method on it when we’re ready to block for the result.

Also notice that the get method throws some checked exceptions, namely ExecutionException (encapsulating an exception that occurred during a computation) and InterruptedException (an exception signifying that a thread executing a method was interrupted):

If you already know the result of a computation, you can use the static completedFuture method with an argument that represents a result of this computation. Then the get method of the Future will never block, immediately returning this result instead.

As an alternative scenario, you may want to cancel the execution of a Future.

Suppose we didn’t manage to find a result and decided to cancel an asynchronous execution altogether. This can be done with the Future‘s cancel method. This method receives a boolean argument mayInterruptIfRunning, but in the case of CompletableFuture it has no effect, as interrupts are not used to control processing for CompletableFuture.

5. Processing Results of Asynchronous Computations

The most generic way to process the result of a computation is to feed it to a function. The thenApply method does exactly that: accepts a Function instance, uses it to process the result and returns a Future that holds a value returned by a function:

If you don’t need to return a value down the Future chain, you can use an instance of the Consumer functional interface. Its single method takes a parameter and returns void.

There’s a method for this use case in the CompletableFuture — the thenAccept method receives a Consumer and passes it the result of the computation. The final future.get() call returns an instance of the Void type.

At last, if you neither need the value of the computation nor want to return some value at the end of the chain, then you can pass a Runnable lambda to the thenRun method. In the following example, after the future.get() method is called, we simply print a line in the console:

6. Combining Futures

The best part of the CompletableFuture API is the ability to combine CompletableFuture instances in a chain of computation steps.

The result of this chaining is itself a CompletableFuture that allows further chaining and combining. This approach is ubiquitous in functional languages and is often referred to as a monadic design pattern.

In the following example we use the thenCompose method to chain two Futures sequentially.

Notice that this method takes a function that returns a CompletableFuture instance. The argument of this function is the result of the previous computation step. This allows us to use this value inside the next CompletableFuture‘s lambda:

The thenCompose method together with thenApply implement basic building blocks of the monadic pattern. They closely relate to the map and flatMap methods of Stream and Optional classes also available in Java 8.

Both methods receive a function and apply it to the computation result, but the thenCompose (flatMap) method receives a function that returns another object of the same type. This functional structure allows composing the instances of these classes as building blocks.

If you want to execute two independent Futures and do something with their results, use the thenCombine method that accepts a Future and a Function with two arguments to process both results:

Notice that the return type of the CompletableFuture.allOf() is a CompletableFuture<Void>. The limitation of this method is that it does not return the combined results of all Futures. Instead you have to manually get results from Futures. Fortunately, CompletableFuture.join() method and Java 8 Streams API makes it simple:

The CompletableFuture.join() method is similar to the get method, but it throws an unchecked exception in case the Future does not complete normally. This makes it possible to use it as a method reference in the Stream.map() method.

8. Handling Errors

For error-handling in a chain of asynchronous computation steps, throw/catch idiom had to be adapted in a similar fashion.

Instead of catching an exception in a syntactic block, the CompletableFuture class allows you to handle it in a special handle method. This method receives two parameters: a result of a computation (if it finished successfully) and the exception thrown (if some computation step did not complete normally).

In the following example we use the handle method to provide a default value when the asynchronous computation of a greeting was finished with an error because no name was provided:

As an alternative scenario, suppose we want to manually complete the Future with a value, as in the first example, but also to have the ability to complete it with an exception. The completeExceptionally method is intended for that. The completableFuture.get() method in the following example throws an ExecutionException with a RuntimeException as its cause:

In the example above we could have handled the exception with the handle method asynchronously, but with the get method we can use a more typical approach of a synchronous exception processing.

9. Async Methods

Most methods of the fluent API in CompletableFuture class have two additional variants with the Async postfix. These methods are usually intended for running a corresponding step of execution in another thread.

The methods without the Async postfix run the next execution stage using a calling thread. The Async method without the Executor argument runs a step using the common fork/join pool implementation of Executor that is accessed with the ForkJoinPool.commonPool() method. The Async method with an Executor argument runs a step using the passed Executor.

Here’s a modified example that processes the result of a computation with a Function instance. The only visible difference is the thenApplyAsync method. But under the hood the application of a function is wrapped into a ForkJoinTask instance (for more information on the fork/join framework, see the article “Guide to the Fork/Join Framework in Java”). This allows to parallelize your computation even more and use system resources more efficiently.