<分区>
我想创建一个 CompletableFuture
已经异常完成。
Scala 通过工厂方法提供了我正在寻找的东西:
Future.failed(new RuntimeException("No 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/