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();
1
  • 1
    Looks fine to me.
    – akuzminykh
    Commented Apr 16, 2021 at 2:11

1 Answer 1

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();
2
  • 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
    Commented Apr 16, 2021 at 14:43
  • 2
    Sure, but I think that hurts readability. (Just like your relatively long lambda in active_sites.forEach, by the way.) Commented Apr 16, 2021 at 17:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.