CompletableFuture-如何在将来的结果中使用局部变量

问题描述

我在Java应用程序中使用CompletableFuture。在以下代码中:

testMethod(List<String> ids)  {

    for(String id : ids) {
        CompletableFuture<Boolean> resultOne = AynchOne(id);
        CompletableFuture<Boolean> resultTwo = AynchTwo(id);
    
CompletableFuture<Boolean> resultThree = resultOne.thenCombine(resultTwo,(Boolean a,Boolean b) -> {
     Boolean andedResult = a && b;
     return andedResult;
    });

resultThree.thenApply(andedResult -> {
     if(andedResult.booleanValue() == true) {
         forwardSucccess(**id**);
      }
      return null;
    });
}

}


void forwardSucccess(String id) {
    // do stuff in the future
}

,“ id”是testMethod()的局部变量,因此我不相信将来的上下文(在thenApply()处)。我在代码清单中看到了forwardSuccess(id),但由于它不是期货的一部分,因此在执行“ forwardSuccess(id)”时可能为null或未定义。

是否可以通过某种方式将“ id”引入期货?

感谢任何想法。

解决方法

我的原始编码几乎是正确的。变量“ id”的值在将来的时间是正确的,因为它在for循环上下文中的值由CompletableFuture的魔力自动转发。如果这对其他人来说很明显,那对我来说不是(这就是为什么我发布了!)。

除了这种认识,我还简化了一些逻辑(基于上述霍尔格先生的有用评论)。

testMethod(List<String> ids)  {

    for(String id : ids) {
        CompletableFuture<Boolean> resultOne = AynchOne(id);
        CompletableFuture<Boolean> resultTwo = AynchTwo(id);

        CompletableFuture<Boolean> resultThree = resultOne.thenCombine(resultTwo,(a,b) -> a && b); 

    resultThree.thenApply(andedResult -> {
        if(andedResult == true) {
            forwardSucccess(id);
        }
        return null;
    });
}


void forwardSucccess(String id) {
    // do stuff in the future
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...