Home > Java > javaTutorial > How to Efficiently Wait for ExecutorService Task Completion?

How to Efficiently Wait for ExecutorService Task Completion?

Patricia Arquette
Release: 2024-12-26 06:27:45
Original
441 people have browsed it

How to Efficiently Wait for ExecutorService Task Completion?

ExecutorService Waiting for Task Completion

In multi-threaded applications, it is often necessary to wait for all tasks submitted to an ExecutorService to complete before proceeding. While crude techniques like polling or constantly checking a global task counter exist, more efficient and elegant solutions are available.

awaitTermination() and shutdown()

The recommended approach involves using the awaitTermination() method of ExecutorService. It allows you to specify a timeout or wait indefinitely for the threads to finish. Here's how it works:

// Create an ExecutorService instance
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);

// Submit tasks as needed
while(...) {
  taskExecutor.execute(new MyTask());
}

// Shutdown the ExecutorService to prevent new tasks from being submitted
taskExecutor.shutdown();

// Wait for threads to complete
try {
  taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
  // Handle any interruptions
}
Copy after login

This method blocks until the threads have completed or the timeout has been reached. You can also specify a finite timeout if you want the application to continue after a specific amount of time, even if some tasks have not finished.

The above is the detailed content of How to Efficiently Wait for ExecutorService Task Completion?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template