I am using ScheduledExecutorService
to run scheduled threads.
I implemented ServletContextListener.contextDestroyed
and invoked ScheduledExecutorService.shutdownNow
and awaitTermination
.
Here is an example:
@Override
public void contextDestroyed(ServletContextEvent servletcontextevent) {
pool.shutdownNow(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(50, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
Still, I am getting the following error from Tomcat 7:
SEVERE: The web application [/servlet] appears to have started a thread named [Timer-0] but has failed to stop it. This is very likely to create a memory leak.
Can this log be ignored? Or I am doing something wrong?
Thanks
Are you sure this error is related to your Thread pool? Judging by thread name 'Timer-0' it probably had been started by some sort of timer.
Also, you shutdownNow() should return you the list of Tasks that still await termination (see JavaDoc). You could build logic to wait more if list is not empty.
You are correctly shutting down your ScheduledExecutorService
. However threads created by ExecutorService
by default follow this naming convention: pool-X-thread-Y
.
Timer-0
threads are created by Timer
class. Look for them in your code and libraries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With