Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 460
TheFunk Avatar asked Apr 16 '21 01:04

TheFunk


People also ask

How to get the result of a function in completablefuture?

To get the result of this CompletableFuture we can call get () method. 3. Running a task in ‘fire and forget’ mode In some scenario we might need to fire the function and the result of the function call is not used in the current function. This can be achieved using CompletableFuture’s runAsync .

How to create a completablefuture in Java?

Creating a CompletableFuture Task First of all to create a new completableFuture task, simply call the constructor Or mark the task as completed by calling the complete method. All the clients waiting for task to complete will get the specified result. To get the result of this CompletableFuture we can call get () method. 3.

How to wait for a function to finish before continuing execution?

Use async/await to Wait for a Function to Finish Before Continuing Execution. Another way to wait for a function to execute before continuing the execution in the asynchronous environment in JavaScript is to use async/wait.

How to wait for a function to execute in the asynchronous environment?

Another way to wait for a function to execute before continuing the execution in the asynchronous environment in JavaScript is to use async/wait.


Video Answer


1 Answers

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();
like image 80
Nicolai Parlog Avatar answered Oct 29 '22 13:10

Nicolai Parlog