8

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

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

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

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

4

2 回答 2

25

我在 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;
}
于 2018-03-22T15:14:24.253 回答
15

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));
}
于 2018-03-22T15:17:14.047 回答