等待 List<CompletableFuture<Void>> 指示所有操作已完成的正确方法

Proper way to wait for List<CompletableFuture<Void>> to indicate all operations have finished

我 运行 有数百个 runAsync() 函数。所有的函数都会修改一些静态可用的列表,因此不需要 return 任何东西。在继续我的处理之前,我想确保它们都完成了。这是合适的等待方式吗?有没有更简单的方法来完成我想做的事情?

List<CompletableFuture<Void>> futures = new ArrayList<>();
active_sites.forEach(site -> site.getEntryPoints().stream().map(EntryPoint::scanEntryPoint).forEach(futures::add));
CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).join();

你可以大大简化它:

CompletableFuture[] scans = active_sites.stream()
    .flatMap(site -> site.getEntryPoints().stream())
    .map(EntryPoint::scanEntryPoint)
    .toArray(CompletableFuture[]::new)
CompletableFuture.allOf(scans).join();