What are the CompletableFuture API improvements in Java 9?

CompletableFuture API is used for asynchronous programming in Java. It means that we can write non-blocking code by running a task on a separate thread than the main() thread and notify the main() thread about its progress, completion or failure. Java 9 introduces a few improvements in CompletableFuture API, they are: "Support for timeouts and delays", "Improved support for subclassing" and "Addition of new factory methods".

Support for timeouts and delays

public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)

The above method has been used to specify if the task does not complete within a certain period of time the program stops and throws TimeoutException.

public CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit)

The above method completes the CompletableFuture with the provided value. If not, it completes before the given timeout.

Improved support for subclassing

public Executor defaultExecutor()

The above method returns the default executor used for async methods that do not show an Executor. It may be overridden in subclasses to return an Executor to give at least one independent thread.

public <U> CompletableFuture<U> newIncompleteFuture()

The above method returns a new incomplete CompletableFuture of the specification to be returned by the CompletionStage method.

New factory Methods

public static <U> CompletableFuture<U> completedFuture(U value)

The above factory method returns a new CompletableFuture that already accomplished with the provided value.

public static <U> CompletionStage<U> completedStage(U value)

The above factory method returns a new CompletionStage that accomplished before with the provided value and is compatible with only those methods available in interface CompletionStage.

Updated on: 21-Feb-2020


Kickstart Your Career

Get certified by completing the course

Get Started