lili
lili

Reputation: 1906

Tomcat 7 and ScheduledExecutorService.shutdown

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

Upvotes: 6

Views: 3127

Answers (2)

maximdim
maximdim

Reputation: 8169

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.

Upvotes: 4

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340933

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.

Upvotes: 1

Related Questions