Search code examples
javamultithreadingcompletable-futurejava-15

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


I am running several hundred functions with runAsync(). All of the functions modify some statically available list and thus do not need to return anything. I want to make sure they all finish before continuing my processing. Is this the appropriate way to wait? Is there a simpler way to accomplish what I'm trying to do?

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();

Solution

  • You can simplify that quite a bit:

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