Home >Java >javaTutorial >How Can I Ensure All Tasks Complete Before Proceeding with an ExecutorService?

How Can I Ensure All Tasks Complete Before Proceeding with an ExecutorService?

Linda Hamilton
Linda HamiltonOriginal
2024-11-28 08:14:13839browse

How Can I Ensure All Tasks Complete Before Proceeding with an ExecutorService?

ExecutorService - A Solution for Waiting for Task Completion

When working with a large number of computational tasks that need to be executed concurrently, it's important to have a mechanism in place to wait for all tasks to finish. This ensures that subsequent actions can be performed only after all tasks have completed.

In your example, where you're attempting to use ExecutorService.wait() to achieve this, you're encountering an IllegalMonitorStateException. This error occurs because wait() is meant to be used when waiting on an object's intrinsic lock, which is not applicable in this scenario.

The simplest solution is to leverage ExecutorService.invokeAll(). This method takes a collection of Callable tasks, executes them in parallel, and returns a list of Future objects. Each Future represents the result of a specific task. By default, invokeAll() will block until all tasks are complete before returning the list of Future objects.

Here's how you can modify your code:

ExecutorService es = Executors.newFixedThreadPool(2);
List<Callable<Object>> tasks = new ArrayList<>();

for (DataTable singleTable : uniquePhrases) {
    tasks.add(Executors.callable(new ComputeDTask(singleTable)));
}

List<Future<Object>> results = es.invokeAll(tasks);

In this updated code, ExecutorService.invokeAll() will wait until all tasks have finished, allowing you to proceed with your subsequent actions confidently.

The above is the detailed content of How Can I Ensure All Tasks Complete Before Proceeding with an ExecutorService?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn