CompletableFuture立即失败

Mat*_*aun 4 java completable-future java-10

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

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

Future.failed(new RuntimeException("No Future!"))
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*aun 10

我找不到Java 8标准库中失败的未来的工厂方法(Java 9修复了Sotirios Delimanolis指出的这个问题),但很容易创建一个:

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)


Sot*_*lis 8

Java 9提供了CompletableFuture#failedFuture(Throwable)哪些

返回CompletableFuture具有给定异常的异常完成的新变量。

那或多或少是你提交的

/**
 * 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));
}
Run Code Online (Sandbox Code Playgroud)