Home  >  Article  >  Java  >  How to Ensure the Termination of Tasks When Shutting Down a Java ExecutorService?

How to Ensure the Termination of Tasks When Shutting Down a Java ExecutorService?

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 07:39:02899browse

How to Ensure the Termination of Tasks When Shutting Down a Java ExecutorService?

ExecutorService Shutdown Termination Strategy

Question:

How do you ensure the termination of running tasks when shutting down a Java ExecutorService?

Answer:

The Oracle API documentation for ExecutorService recommends the following approach:

<code class="java">void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks
   try {
     // Wait for existing tasks
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel executing tasks
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     pool.shutdownNow();
     Thread.currentThread().interrupt();
   }
}</code>

Shutdown Related Methods:

  • shutdown: Initiates orderly shutdown, executing previously submitted tasks and rejecting new tasks.
  • shutdownNow: Attempts to stop all running tasks and return a list of tasks awaiting execution.
  • awaitTermination: Blocks until all tasks complete or until a timeout or interruption occurs.

Enhanced Termination Waiting:

If the pool takes more time to shut down, you can change:

<code class="java">if (!pool.awaitTermination(60, TimeUnit.SECONDS))</code>

to:

<code class="java">while (!pool.awaitTermination(60, TimeUnit.SECONDS))</code>

This will continue waiting indefinitely until termination is achieved.

The above is the detailed content of How to Ensure the Termination of Tasks When Shutting Down a Java 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