用Java 8 CompletableFuture替换Futures.successfulAsList? [英] Replace Futures.successfulAsList with Java 8 CompletableFuture?

查看:461
本文介绍了用Java 8 CompletableFuture替换Futures.successfulAsList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找替代Guava的规范代码 Futures.successfulAsList() 8的 CompletableFuture 代码。

I am Looking for canonical code to replace Guava's Futures.successfulAsList() with Java 8's CompletableFuture code.

我认为 CompletableFuture.allOf() 似乎是 Futures.allAsList() ,但我看不到任何类似 successfulAsList()

推荐答案

CompletableFuture.allOf(...)实际上更接近 successfulAsList()而不是 allAsList()

CompletableFuture.allOf(…) is actually closer to successfulAsList() than allAsList().

确实, allOf()只有在所有给定的期货完成后才能完成,无论是价值还是例外。然后,您可以检查每个未来以检查它是如何完成的(例如,在以下 thenAccept() / thenApply()) 。

Indeed, allOf() only completes after all the given futures have completed, be it with a value or an exception. You can then inspect each future to check how it completed (e.g. in a following thenAccept()/thenApply()).

allAsList() CompletableFuture 因为任何输入期货失败都会失败。但是,您可以使用 allOf()的组合来实现它,并使用 exceptionally()将每个输入的未来链接起来将使返回的未来allOf()立即失败:

allAsList() does not have a close equivalent in CompletableFuture because it should fail as soon as any of the input futures fails. However, you could implement it 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;
    }));

这篇关于用Java 8 CompletableFuture替换Futures.successfulAsList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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