6

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();
TheFunk
  • 981
  • 11
  • 39

1 Answers1

6

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();
Nicolai Parlog
  • 47,972
  • 24
  • 125
  • 255
  • That is a good deal simpler. Could I get rid of the local variable too? Perhaps something like: `CompletableFuture.allOf(active_sites.stream().flatMap(site -> site.getEntryPoints().stream()).map(EntryPoint::scanEntryPoint).toArray(CompletableFuture[]::new)).join();` – TheFunk Apr 16 '21 at 14:43
  • 2
    Sure, but I think that hurts readability. (Just like your relatively long lambda in `active_sites.forEach`, by the way.) – Nicolai Parlog Apr 16 '21 at 17:21