logo

CompletableFuture API Improvements


Show

The CompletableFuture class was introduced in Java 8 to represent the longer term which may be completed by setting its value and standing explicit. It is often used as java.util.concurrent.CompletionStage. It supports dependent functions and actions which get triggered upon the future's completion. CompletableFuture API has been enhanced further In java 9. Below are the applicable replacements are done to the API.

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

Support for Delays and Timeouts

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

This way finishes this CompletableFuture with the mentioned value if not or else completed prior to the mentioned timeout.

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

This way exceptionally finishes this CompletableFuture with a TimeoutException if not or else finishes prior to the mentioned timeout.

Improved support for Subclassing

public Executor defaultExecutor()

It gives back the default Executor to make use of async procedures that do not define an Executor. This procedure may be overridden in subclasses to give back an Executor to give one independent thread at least.

public <U> CompletableFuture<U> newIncompleteFuture()

Gives back a new unfinished CompletableFuture of the variety to be returned by a CompletionStage procedure. Subclasses of the CompletableFuture class must override this procedure to give back an example of the identical class as this CompletableFuture. The default execution gives back an example of the class CompletableFuture.

New Factory Methods

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

This factory procedure gives back a new CompletableFuture which is previously finished with the defined value.

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

This factory procedure gives back a new CompletionStage which is previously finished with the defined value and supports only those procedures currently in interface CompletionStage.

public static <U> CompletionStage<U> failedStage(Throwable ex)

This factory procedure gives back a new CompletionStage which is previously completed exceptionally with the defined exception and supports only those procedures currently in interface CompletionStage.