CompletableFuture立即失败

时间:2018-03-22 15:14:24

标签: java completable-future java-10

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

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

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

Java 10或更高版本中是否存在类似内容?

2 个答案:

答案 0 :(得分:6)

我无法在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;
}

答案 1 :(得分:4)

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