我想实现 CompletableFuture.allOf()和 CompletableFuture.anyOf()的混合体只要所有要素成功完成,future就会成功完成,或者一旦任何要素异常完成,future就会异常完成(相同的例外)。如果有多个元素失败,则返回其中任何一个例外就足够了。
I want to implement a hybrid of CompletableFuture.allOf() and CompletableFuture.anyOf() where the returned future completes successfully as soon as all of the elements complete successfully, or it completes exceptionally (with the same exception) as soon as any of the elements complete exceptionally. In the case of multiple elements failing, returning the exception of any of them is sufficient.
我有一个任务需要汇总由 CompletableFuture s列表返回的子结果,但是一旦其中任何一个失败,该任务应停止等待。我知道子任务会继续运行,没关系。
I have a task that needs to aggregate sub-results returned by a list of CompletableFutures, but that task should stop waiting as soon as any of them fails. I understand that the sub-tasks will keep on running and that's okay.
我发现等待未来列表,它最初看起来像是一个重复的问题,但可接受的答案使用 CompletionService ,它需要 Callable 或 Runnable 作为输入。我正在寻找一种将已经运行的 CompletionStage s作为输入的解决方案。
I found Waiting on a list of Future which initially seems like a duplicate question but the accepted answer uses CompletionService which requires Callable or Runnable as input. I am looking for a solution that takes already-running CompletionStages as input.
推荐答案此问题实际上与替换期货相似。使用Java 8 CompletableFuture的successAsList吗?
尽管问题并不完全相同,但相同的答案(来自我自己)应该可以满足您的需求。
Although the question is not exactly the same, the same answer (from myself) should satisfy your needs.
您可以结合使用 allOf()来实现此功能,并使用 exceptionally链接每个输入的未来( )会使 allOf()返回的未来立即失败:
You can implement this with a combination of allOf() and chaining each input future with an exceptionally() that would make the future returned by allOf() immediately fail:
CompletableFuture<String> a = …, b = …, c = …; CompletableFuture<Void> allWithFailFast = CompletableFuture.allOf(a, b, c); Stream.of(a, b, c) .forEach(f -> f.exceptionally(e -> { allWithFailFastpleteExceptionally(e); return null; }));更多推荐
如何实现CompletableFuture.allOf(),一旦任何期货失效,它就会异常完成?
发布评论