Java 我如何跳过异常完成的期货
下面是整合可完成未来的代码片段。下面的问题是,我的一些未来正在异常完成,所以总体而言,我的结果是异常完成 从java文档中我了解到,当任何未来抛出异常时,allof都会返回异常 返回一个新的CompletableFuture,该Future在所有给定CompletableFutures完成时完成。如果任何给定CompletableFutures异常完成,则返回的CompletableFutures也会异常完成,CompletionException将此异常作为其原因 但我看不到任何其他api可以帮助我在一切完成后获得未来 有人能帮我吗?有人能给我一些线索吗?我怎么能跳过正在异常完成的期货呢。换言之,我想得到毫无例外地完成的未来Java 我如何跳过异常完成的期货,java,concurrency,completable-future,Java,Concurrency,Completable Future,下面是整合可完成未来的代码片段。下面的问题是,我的一些未来正在异常完成,所以总体而言,我的结果是异常完成 从java文档中我了解到,当任何未来抛出异常时,allof都会返回异常 返回一个新的CompletableFuture,该Future在所有给定CompletableFutures完成时完成。如果任何给定CompletableFutures异常完成,则返回的CompletableFutures也会异常完成,CompletionException将此异常作为其原因 但我看不到任何其他api可以
CompletableFuture<List<Pair<ExtensionVO, GetObjectResponse>>> result =
CompletableFuture.allOf(
completableFutures.toArray(new CompletableFuture<?>[completableFutures.size()]))
.thenApply(
v ->
completableFutures
.stream()
.map(CompletableFuture::join)
.filter(Objects::nonNull)
.collect(Collectors.toList()));
可完成的未来结果=
CompletableFuture.allOf(
completableFutures.toArray(新的completableFutures[completableFutures.size()]))
.然后申请(
v->
完全期货
.stream()
.map(CompletableFuture::join)
.filter(对象::非空)
.collect(Collectors.toList());
首先,您必须使用handle
链接一个即使在异常情况下也能产生结果的函数,然后使用.filter(f->!f.iscompletedexeceptional())
在调用join()
之前跳过异常完成的期货:
但这可能只会对非常大的列表产生回报,如果有的话。您能提供
MVCE
?
CompletableFuture<List<Pair<ExtensionVO, GetObjectResponse>>> result =
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture<?>[0]))
.handle((voidResult,throwable) ->
completableFutures
.stream()
.filter(f -> !f.isCompletedExceptionally())
.map(CompletableFuture::join)
.filter(Objects::nonNull)
.collect(Collectors.toList()));
CompletableFuture<List<Pair<ExtensionVO, GetObjectResponse>>> result =
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture<?>[0]))
.handle((voidResult, throwable) ->
(throwable == null?
completableFutures.stream():
completableFutures.stream().filter(f -> !f.isCompletedExceptionally()))
.map(CompletableFuture::join)
.filter(Objects::nonNull)
.collect(Collectors.toList()));