Home >Java >javaTutorial >How to Efficiently Wait for All ExecutorService Tasks to Finish?
Waiting for ExecutorService Tasks to Finish
Question:
How can one efficiently wait for all tasks submitted to an ExecutorService to complete? The specific use case involves computational tasks executed on multiple cores.
Background:
The given code snippet utilizes ExecutorService.wait(), but it fails with an IllegalMonitorStateException. Despite successful task execution, the wait operation appears to encounter an issue.
Answer:
ExecutorService.invokeAll()
The recommended solution is to use ExecutorService.invokeAll(). It provides a straightforward method to wait for all tasks to complete. Here's a modified code example:
ExecutorService es = Executors.newFixedThreadPool(2); List<Callable<Object>> todo = new ArrayList<>(singleTable.size()); for (DataTable singleTable: uniquePhrases) { todo.add(Executors.callable(new ComputeDTask(singleTable))); } List<Future<Object>> answers = es.invokeAll(todo);
invokeAll() Behavior
invokeAll() will block until all tasks are finished. The resulting answers collection contains Futures representing each task's status and potential return value. By default, wrapped by Executors.callable(), these Futures will return null. However, you can modify ComputeDTask to implement Callable
Benefits:
Using invokeAll() simplifies the code and avoids the potential race condition associated with wait(). It also allows for reusability of the ExecutorService for multiple cycles.
Related Questions:
For further clarification, consider the following related questions on Stack Overflow:
The above is the detailed content of How to Efficiently Wait for All ExecutorService Tasks to Finish?. For more information, please follow other related articles on the PHP Chinese website!