Home > Java > javaTutorial > body text

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

Barbara Streisand
Release: 2024-10-24 07:39:02
Original
898 people have browsed it

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>
Copy after login

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>
Copy after login

to:

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

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!

source:php
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