【问题标题】:CompletableFuture is Not waiting for child threadsCompletableFuture 不等待子线程
【发布时间】:2023-01-23 17:43:10
【问题描述】:

我正在尝试等待 processor.processFiles() 完成,该方法返回 void,它是一个 @Async 方法。忙等待逻辑不会导致进程等待方法完成。 有人可以指出我错过了什么吗?

try{

filesList.forEach(files -> {
List<CompletableFuture<Void>> completableFutures  = new ArrayList<>();

files.forEach(file-> {
    CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> 
    processor.processFiles());
    completableFutures.add(completableFuture);

});
    while(true) {

    Thread.sleep(5000);
    boolean isComplete = completableFutures.stream().allMatch(result -> result.isDone() == true);

    if(isComplete){
    break;
}
    LOGGER.info("processing the file...");

}

});

} 
catch(Exception e){


}

finally{
    closeConnections();

}

}

【问题讨论】:

  • 您可以使用 CompletableFuture.allOf(completableFutures).get() 摆脱该循环。这将创建一个新的CompletableFuture,只有在所有给定的CompletableFutures结束时才会结束; get() 将返回 null,因为这是其通用类型的唯一有效值 - Void。忽略它。

标签: java asynchronous completable-future


【解决方案1】:

因为您只是在完成处理后才将期货添加到列表中。您必须将它们添加到未来本身之外,一旦未来被分派(并且可能在处理开始之前)。

List<CompletableFuture<Void>> completableFutures  = new ArrayList<>();

files.forEach(file-> {
    CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> processor.processFiles());
    completableFutures.add(completableFuture);

    // ...
}

【讨论】:

  • 格式使其更难阅读,但这正是 sharad 已经做到的。如果我删除一个换行符,您的代码与最初发布的代码相同。
猜你喜欢
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-08
  • 2020-08-12
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
相关资源
最近更新 更多