CompletableFuture 立即失败

CompletableFuture immediate failure

我想创建一个已经异常完成的CompletableFuture

Scala 通过工厂方法提供了我正在寻找的东西:

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

在 Java 10 或更高版本中是否有类似的东西?

我无法在 Java 8 的标准库中找到失败的 future 的工厂方法(Java 9 修复了这个问题,正如 所指出的那样),但是创建一个很容易:

/**
 * Creates a {@link CompletableFuture} that has already completed
 * exceptionally with the given {@code error}.
 *
 * @param error the returned {@link CompletableFuture} should immediately
 *              complete with this {@link Throwable}
 * @param <R>   the type of value inside the {@link CompletableFuture}
 * @return a {@link CompletableFuture} that has already completed with the
 * given {@code error}
 */
public static <R> CompletableFuture<R> failed(Throwable error) {
    CompletableFuture<R> future = new CompletableFuture<>();
    future.completeExceptionally(error);
    return future;
}

Java 9 提供 CompletableFuture#failedFuture(Throwable) 其中

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

这或多或少是您提交的内容

/**
 * 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));
}