Search code examples
javaspringjavabeansshutdown

How to shutdown ThreadPoolExecutor in spring bean when tomcat is shutdown?


I create a threadpoolexecutor in a spring bean, so I need to shutdown this executor when tomcat is shutdown.

     public class PersistBO implements InitializingBean {

private ThreadPoolExecutor executer;

public void shutdownExecutor() {
    executer.shutdown();
}

@Override
public void afterPropertiesSet() throws Exception {
    taskQueue = new LinkedBlockingQueue<Runnable>(queueLength);
    executer = new ThreadPoolExecutor(minThread, maxThread, threadKeepAliveTime, 
            TimeUnit.SECONDS, taskQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
}

I have searched solution on google and get a result. That is to add a shutdownhook to java.lang.runtime. However, the java docs says java.lang.Runtime#shutdownHook is called when the last non-daemon thread exits. So it is a dead lock. Is there any solution to shutdown executor in spring bean?


Solution

  • I guess lifecycle of the executor should depend on lifecycle of your application, not Tomcat as a whole. You can stop your application while Tomcat is still running, therefore Runtime.shutdownHook() is not applicable.

    Since you already use Spring and its InitializingBean for initialization, you can use DispasableBean to perform cleanup when application context is being closed:

    public class PersistBO implements InitializingBean, DisposableBean { 
        public void destroy() {
            shutdownExecutor();
        }
        ...
    }