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!
Use a CountDownLatch.
countDown
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.
You must shut the Executor down with shutDown
and then wait until all jobs have been processed with awaitTermination
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With