Java 8 CompletableFuture-如何在未来结果中使用局部变量

Java 8 CompletableFuture-如何在未来结果中使用局部变量,java-8,future,completable-future,Java 8,Future,Completable Future,我在java应用程序中使用CompletableFuture。在以下代码中: testMethod(List<String> ids) { for(String id : ids) { CompletableFuture<Boolean> resultOne = AynchOne(id); CompletableFuture<Boolean> resultTwo = AynchTwo(id); Comple

我在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
}
testMethod(列出ID){
用于(字符串id:ids){
CompletableFuture resultOne=AynchOne(id);
CompletableFuture resultTwo=AynchTwo(id);
CompletableFuture resultThree=ResultTone.thenCombine(结果二,(布尔a,布尔b)->{
布尔ANDRESULT=a&&b;
返回和结果;
});
结果三个。然后应用(和结果->{
if(andedResult.booleanValue()=真){
ForwardSuccess(**id**);
}
返回null;
});
}
}
void forwardsuccess(字符串id){
//在将来做一些事情
}
,则“id”是testMethod()的本地属性,因此我不相信未来的上下文(在thenApply())。我在代码片段中看到了forwardSuccess(id),但由于它不是futures的一部分,在执行“forwardSuccess(id)”时可能为null或未定义

有没有办法将“id”引入期货市场


谢谢你的建议。

我最初的编码几乎是正确的。变量“id”的值在将来是正确的,因为它在for循环上下文中的值是由CompletableFuture的魔力自动转发的。如果这对其他人来说是显而易见的,那对我来说就不是了(这就是为什么我要发帖子!)

除此之外,我还简化了一些逻辑(基于上面霍尔格先生的有用评论)

testMethod(列出ID){
用于(字符串id:ids){
CompletableFuture resultOne=AynchOne(id);
CompletableFuture resultTwo=AynchTwo(id);
CompletableFuture resultThree=ResultTone.thenCombine(结果二,(a,b)->a和b);
结果三个。然后应用(和结果->{
如果(andedResult==true){
转发成功(id);
}
返回null;
});
}
void forwardsuccess(字符串id){
//在将来做一些事情
}

为什么这么复杂?
CompletableFuture resultThree=resultOne.then合并(resultTwo,(a,b)->a&b);
resultThree.then接受(andedResult->{if(andedResult){forwardsuccess(id);}}};
或者只需一步完成:
resultOne.then接受(resultTwo,(a,b)->{if(a&b)forwardsuccess(id)}
以这种方式使用
id
时,将捕获并使用它的值,因此没有问题。这就是为什么变量必须是有效的最终变量,即不允许更改其值。请考虑在每个循环迭代中使用一个新变量。
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
}