0

I have a thread-pool in my application which I want to shutdown only when application stops. I tried 3 ways:

1.Shutting down in context destroyed:

@Override
public void contextDestroyed(ServletContextEvent sce) {
    System.out.println("CALLING CONTEXT DESTROYED.");
    PersistSigningExecutor.getService().shutdown();
}

2.Shutting down in destroy method of any servlet:

@Override
public void destroy() {   
    super.destroy();
    System.out.println("SHUTTING DOWN THREAD-POOLS");  
    PersistSigningExecutor.getService().shutdown();
}  

3.Adding shutdown hook in contextInitialised

@Override
public void contextInitialized(ServletContextEvent sce) {       
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    System.out.println("SHUTTING DOWN THREAD-POOLS");                        
                    PersistSigningExecutor.getService().shutdown();

            }
        });

}

But none of them are working. I am not seeing any print statements. And also at the end I am getting log saying :

SEVERE: The web application [/app] appears to have started a thread named [pool-1-thread-1] but has failed to stop it. This is very likely to create a memory leak.

which means the thread is still not shutdown. How to shutdown this thread-pool properly when server is shutdown or application is undeployed?

Akhil
  • 533
  • 2
  • 11
  • 26

1 Answers1

0

make the thread demon (setDamon(boolean)), so that it will stop when jvm starts shutting down basically demon thread does not prevent JVM to shutdown.

Or else if you plan to use ExecutorService then you need to call shutdown() or shutdownNow().

Let me know if you need more help.

Trying
  • 14,004
  • 9
  • 70
  • 110
  • This fails if the OP needs the threads to end currently running tasks. `daemon` threads stop in the same way a `Thread.stop` does. So if there is any needed coordination to 'shutdown' this will fail. – John Vint Mar 18 '15 at 14:01