java - CompletableFuture 立即失败

标签 java completable-future java-10

<分区>

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

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

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

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

最佳答案

我在 Java 8 的标准库中找不到一个失败的 future 的工厂方法(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;
}

关于java - CompletableFuture 立即失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49432257/

相关文章:

java - ExecutorService.submit(Task) vs CompletableFuture.supplyAsync(Task, Executor)

Java 10 和 Mac 应用程序菜单

java - 返回主要 Activity

java - 在 Java 中将 32 位 float 分配给 4 个整数(RGBA)

java - 如何使用 Netty 关闭异步 Http 请求的 AsyncHttpClient?

java - 用于 Java CompletableFuture 组合的线程?

java - 多个java版本JDK1.8和JDK10之间切换

java - java 10 和 kotlin 中的 “var”

java - 如何判断哪个派生类调用重写基方法

java - 沿着 LibGDX 中的路径 vector 偏移 Sprite