如何实现CompletableFuture.allOf(),一旦任何期货失效,它就会异常完成? [英] How to implement CompletableFuture.allOf() that completes exceptionally once any of the futures fail?

查看:1554
本文介绍了如何实现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.

我发现< a href = https://stackoverflow.com/q/19348248/14731>等待未来列表,它最初看起来像是一个重复的问题,但可接受的答案使用 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 -> {
        allWithFailFast.completeExceptionally(e);
        return null;
    }));

这篇关于如何实现CompletableFuture.allOf(),一旦任何期货失效,它就会异常完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆