CompletableFuture<String> future = CompletableFuture.completedFuture(null);
for(int _retrial = 1 ; _retrial <= getRetrialCountBasedOnSomeLogic() ; _retrial++) {
int finalRetrial = _retrial;
future = future
.thenCompose(lastRetrialStatus -> {
if(Strings.isnullOrEmpty(lastRetrialStatus) || (!"SUCCESS".equals(lastRetrialStatus))) {
return doSomeCalculations(finalRetrial);
} else {
return CompletableFuture.completedFuture(null);
}
})
.handle((response,throwable) -> {
if(throwable != null) {
throwable = CompletableFutures.unwrapCompletionStateException(throwable);
return throwable.getMessage();
}
return "SUCCESS";
});
}
return future;
我最近开始在上面的代码中从事completablefutures的工作-如您所见,我正在用for循环链接期货。如果句柄返回“ SUCCESS”,我希望链停止。像这样:
CompletableFuture<String> future = CompletableFuture.completedFuture(null);
for(int _retrial = 1 ; _retrial <= getRetrialCountBasedOnSomeLogic() ; _retrial++) {
int finalRetrial = _retrial;
future = future
.thenCompose(lastRetrialStatus -> doSomeCalculations(finalRetrial))
.handle((response,throwable) -> {
if(throwable != null) {
throwable = CompletableFutures.unwrapCompletionStateException(throwable);
return throwable.getMessage();
}
**Its a success,I dont need to look for any further passes of this loop. Lets end here by returning "SUCCESS"**
});
}
return future;