Java 9 Improved CompletableFuture API
Java 8 introduced the CompletableFuture<T>
class, which could be a definitive completed version of java.util.concurrent.Future<T>
(setting its value and status) or used as java.util.concurrent.CompletionStage
. It supports triggering dependent functions and actions upon future completion. Java 9 introduced several improvements to CompletableFuture:
Java 9 made improvements to CompletableFuture:
- Support for delays and timeouts
- Enhanced support for subclassing
- New factory methods
Support for Delays and Timeouts
public CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit)
Completes this CompletableFuture with the given value if not otherwise completed before the specified timeout (in java.util.concurrent.TimeUnit, such as MILLISECONDS). Returns this CompletableFuture.
public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)
Completes this CompletableFuture with a java.util.concurrent.TimeoutException if not otherwise completed within the specified timeout, and returns this CompletableFuture.
Enhanced Support for Subclassing
Numerous improvements were made to make CompletableFuture easier to inherit. For example, you might want to override the new public Executor defaultExecutor()
method to replace the default executor.
Another new method that makes subclassing easier is:
public <U> CompletableFuture<U> newIncompleteFuture()
New Factory Methods
Java 8 introduced the <U> CompletableFuture<U> completedFuture(U value)
factory method to return a CompletableFuture
completed with the given value. Java 9 complements this with a new <U> CompletableFuture<U> failedFuture(Throwable ex)
method to return a CompletableFuture
completed with the given exception.
Additionally, Java 9 introduced the following pair of stage-oriented factory methods, returning completed or exceptionally completed completion stages:
<U> CompletionStage<U> completedStage(U value)
: Returns a newCompletionStage
completed with the specified value and supports only the interfaces inCompletionStage
.<U> CompletionStage<U> failedStage(Throwable ex)
: Returns a new CompletionStage completed exceptionally with the specified exception and supports only the interfaces in CompletionStage.