如何实现CompletableFuture.allOf(),一旦任何期货失效,它就会异常完成?

编程入门 行业动态 更新时间:2024-10-11 11:22:08
本文介绍了如何实现CompletableFuture.allOf(),一旦任何期货失效,它就会异常完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想实现 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(),一旦任何期货失效,它就会异常完成?

本文发布于:2023-11-24 23:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1627349.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:就会   如何实现   期货   异常   allOf

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!