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

1.6k Views Asked by At

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

There are 1 best solutions below

2
On BEST ANSWER

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