Java 9 Improved CompletableFuture API

Java 9 新特性Java 9 New Features

Java 8 introduced theCompletableFuture<T>class, which may bejava.util.concurrent.Future<T>explicitly completed (with its value and status set), or may be used asjava.util.concurrent.CompleteStage. Supports triggering dependent functions and actions when the future completes. Java 9 introduced someCompletableFutureimprovements:

Java 9CompletableFuturemade improvements:

  • Support delays and timeouts
  • Improved support for subclassing
  • New factory methods

Support delays and timeouts

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

Intimeout(unit injava.util.concurrent.Timeunits units, e.g., MILLISECONDS) before completing this CompletableFuture with the given value. Return this CompletableFuture.

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

If not completed within the given timeout, complete this CompletableFuture with java.util.concurrent.TimeoutException and return this CompletableFuture.

Enhanced support for subclassing

Made many improvements so thatCompletableFuturecan be subclassed more easily. For example, you might want to override the newpublic Executor defaultExecutor()method instead of the defaultexecutor。

Another new method that makes subclassing easier is:

public <U> CompletableFuture<U> newIncompleteFuture()

New factory methods

Java 8 introduced a<U> CompletableFuture<U> completedFuture(U value)factory method to return a ... that has already completed with the given valueCompletableFuture. Java 9 supplemented this method with a new<U> CompletableFuture<U> failedFuture(Throwable ex)that can return a ... completed with the given exceptionCompletableFuture。

In addition, 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 new ... completed with the specified valueCompletionStage, and only supportsCompletionStagethe interfaces in
  • <U> CompletionStage<U> failedStage(Throwable ex): Returns a new ... completed with the specified exceptionCompletionStage, and only supportsCompletionStagethe interfaces in

Java 9 新特性Java 9 New Features

Other Extensions