我该如何跳过即将完成的期货

下面的代码段巩固了可完成的未来。下面的问题是我的某些期货交易异常顺利,因此总体上我的交易异常顺利。

从Java文档中我了解到将来任何抛出异常时allof都会返回异常 “返回一个当所有给定CompletableFuture完成时完成的新CompletableFuture。如果任何给定CompletableFuture都异常完成,则返回的CompletableFuture也会这样做,并且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()));
quguangliang 回答:我该如何跳过即将完成的期货

首先,您必须使用handle链接一个即使在特殊情况下也可以产生结果的函数,然后在调用.filter(f -> !f.isCompletedExceptionally())之前使用join()跳过异常完成的期货:

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

原则上,您可以使用throwable确定是否发生异常,仅在必要时执行isCompletedExceptionally()检查:

CompletableFuture<List<Pair<ExtensionVO,throwable) ->
            (throwable == null?
                completableFutures.stream():
                completableFutures.stream().filter(f -> !f.isCompletedExceptionally()))
            .map(CompletableFuture::join)
            .filter(Objects::nonNull)
            .collect(Collectors.toList()));

但是,如果有的话,这可能只对非常大的列表有用。

本文链接:https://www.f2er.com/2941579.html

大家都在问