Java 8 CompletableFuture.allOf(CompletableFuture<?>...cfs)
将返回 CompletableFuture
当所有给定的 future 完成时完成,或者抛出 CompletionException
如果其中一个 future 完成时出现异常。
如果我的其中一个 future 完成时出现异常,将 CompletableFuture.allOf
等待剩余的 future 完成后再抛出 CompletionException
还是会取消剩余的 future ?
如果它等待所有 future 完成,有什么办法让它在任何 future 抛出异常时立即返回并取消剩余的 future 吗?
最佳答案
If one of my futures completes with an exception, will
CompletableFuture.allOf
wait for the remaining futures to complete before throwing theCompletionException
是的,它仍然会等待所有 future 完成。
您可以使用此辅助方法创建一个 CompletableFuture
,一旦任何 future 完成,它就会异常完成。
public static CompletableFuture allOfTerminateOnFailure(CompletableFuture<?>... futures) {
CompletableFuture<?> failure = new CompletableFuture();
for (CompletableFuture<?> f: futures) {
f.exceptionally(ex -> {
failure.completeExceptionally(ex);
return null;
});
}
return CompletableFuture.anyOf(failure, CompletableFuture.allOf(futures));
}
如果您还想取消所有其他 future(如果其中一个 future 异常完成),您可以在从此方法返回之前执行以下操作:
failure.exceptionally(ex -> {
Arrays.stream(futures).forEach(f -> f.cancel(true));
return null;
});
关于java - CompletableFuture.allOf 在抛出异常时取消其他 future,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58491368/