When leveraging ExecutorService, a developer may encounter a need to pause execution until all assigned tasks are complete. This inquiry explores the simplest approach for achieving this objective.
Question:
Execute a multitude of computational tasks, one per core, and pause execution until their completion. Current implementation utilizes ExecutorService.execute() and es.wait(), but faces an IllegalMonitorStateException.
Answer:
Employ ExecutorService.invokeAll(), a straightforward solution that accomplishes the desired functionality with a single line of code:
List<Callable<Object>> todo = new ArrayList<Callable<Object>>(singleTable.size()); for (DataTable singleTable: uniquePhrases) { todo.add(Executors.callable(new ComputeDTask(singleTable))); } List<Future<Object>> answers = es.invokeAll(todo);
invokeAll() pauses execution until all tasks are completed, rendering manual shutdown and awaitTermination() unnecessary. This approach aligns with reusable ExecutorService instances across multiple executions.
For further exploration of related topics, consult these references:
The above is the detailed content of How to Efficiently Await Task Completion Using ExecutorService?. For more information, please follow other related articles on the PHP Chinese website!