Search code examples
javacompletable-futurejava-10

CompletableFuture immediate failure


I'd like to create a CompletableFuture that has already completed exceptionally.

Scala provides what I'm looking for via a factory method:

Future.failed(new RuntimeException("No Future!"))

Is there something similar in Java 10 or later?


Solution

  • Java 9 provides CompletableFuture#failedFuture(Throwable) which

    Returns a new CompletableFuture that is already completed exceptionally with the given exception.

    that is more or less what you submitted

    /**
     * Returns a new CompletableFuture that is already completed
     * exceptionally with the given exception.
     *
     * @param ex the exception
     * @param <U> the type of the value
     * @return the exceptionally completed CompletableFuture
     * @since 9
     */
    public static <U> CompletableFuture<U> failedFuture(Throwable ex) {
        if (ex == null) throw new NullPointerException();
        return new CompletableFuture<U>(new AltResult(ex));
    }