Replace Futures.successfulAsList with Java 8 CompletableFuture?

為{幸葍}努か 提交于 2019-12-10 15:15:44

问题


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

I think CompletableFuture.allOf() seems like a replacement for Futures.allAsList(), but I don't see anything quite like successfulAsList().


回答1:


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

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() 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;
    }));


来源:https://stackoverflow.com/questions/43330764/replace-futures-successfulaslist-with-java-8-completablefuture

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!