简体   繁体   中英

How to kill non-daemon threads created by library when quitting?

My application is running in tomcat, every time I stop tomcat it warns me there are lots of threads fail to shutdown. These threads are created by libraries my application use, I have no idea how to kill them. This issue leads tomcat process still live after I call bin/shutdown.sh shipped with tomcat.

can anybody help? thanks

Those libraries should also expose corresponding "shutdown", "stop", etc. methods you will need to call. Check their respective documentations or source.

You can also use jConsole or VisualVM to see what threads are alive after you try to shutdown your machine. If you're lucky your libraries will name them intelligently (RMQ doesn't by default, for instance), and you can tell what's left.

You can use a class that implements ServletContextListener and annotate it with @WebListener() (or indicate it's a listener in web.xml for earlier versions of Tomcat).

The interface has two methods contextInitialized and contextDestroyed where you can - in your implementation - do initialization and cleanup of any libraries or classes that might be spawning threads or otherwise need special tending. A Java Servlet Container like Tomcat will call both of the methods as part of a webapps start/stop life-cycle. Example:

@WebListener()
public class RestartListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //some initialization code here
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        MemcachedManager.shutdown();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM