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:
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!