Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java 9 Improved CompletableFuture API

Java 9 Improved CompletableFuture API

Java 9 New Features Java 9 New Features

Java 8 introduced CompletableFuture class, which may be java.util.concurrent.Future an explicitly completed version (with its value and state set), or it may be used as a java.util.concurrent.CompletionStage. It supports triggering dependent functions and actions when the future completes. Java 9 introduces someCompletableFuture improvements to

Java 9 has made improvements to CompletableFuture :

Support for delays and timeouts

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

in timeout(with the unit in java.util.concurrent.Timeunits units , for example MILLISECONDS) completes this CompletableFuture with the given value. Returns this CompletableFuture.

public CompletableFuture orTimeout(long timeout, TimeUnit unit)

If it is not completed within the given timeout, completes this CompletableFuture with a java.util.concurrent.TimeoutException, and returns this CompletableFuture.

Enhanced support for subclassing

has been improved in many ways so that CompletableFuture it can be subclassed more easily. For example, you may want to override the new public Executor defaultExecutor() method instead of the default executor.

Another new method that makes subclassing easier is:

public  CompletableFuture newIncompleteFuture()

New factory methods

Java 8 introduced CompletableFuture the completedFuture(U value) factory method to return a CompletableFuture already completed with the given value. Java 9 supplements it with a new CompletableFuture failedFuture(Throwable ex), which returns a CompletableFuture completed with the given exception.

In addition, Java 9 introduces the following pair of stage-oriented factory methods that return completed or exceptionally completed completion stages:

  • CompletionStage completedStage(U value): returns a new CompletionStage completed with the specified value, and only supports the interfaces in CompletionStage.
  • CompletionStage failedStage(Throwable ex): returns a new CompletionStage completed with the specified exceptionCompletionStage , and only supports CompletionStage 's interfaces.

Java 9 New Features Java 9 New Features