Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for all callables to finish executing before proceeding?

I have the following code hashed out:

public class MyCallable implements Callable<Long> {
    @Override
    public Long call() throws Exception {
        // Do stuff...
    }
}

public class MyController {
    private ExecutorService executor = Executos.newCachedTreadPool();

    public Long concurrentDoStuff() {
        List<MyCallable> workers = makeWorkers();

        List<Long> allResults = new ArrayList<Long>();
        for(MyCallable worker : workers) {
            Future<Long> workerResults = executor.submit(worker);

            try {
                allResults.add(workerResults.get());
            } catch(InterruptedException ie) {
                // Handle...
            } catch(ExecutionException ee) {
                // Handle...
            }
        }

        // Question: how do I pause here and wait for all workers to finish?
    }
}

After the for-loop, I want to wait for all workers to finish before proceeding any further. What's the best/safest/most-efficient way to do this? Thanks in advance!

like image 215
IAmYourFaja Avatar asked May 10 '13 13:05

IAmYourFaja


2 Answers

Use a CountDownLatch.

  • Initialize it with the number of workers
  • Pass a reference to the latch in the worker constructor
  • When the worker is done, call countDown
  • Call await in the main thread and it will block until the workers are done.

This is a more general-purpose solution than using methods on the executor service.

like image 154
Alex Avatar answered Oct 26 '22 18:10

Alex


You must shut the Executor down with shutDown and then wait until all jobs have been processed with awaitTermination.

like image 25
Ralf H Avatar answered Oct 26 '22 17:10

Ralf H