Tomcat shutdown listener release the database connection pool

Because the code is updated frequently to restart the development of Tomcat, encountered a problem: after performing shutdown script, Tomcat process still has not closed (but HTTP service has been stopped), you need to execute the kill command job manually. Check some information combined with experience, should be the cause of a problem connecting to the database connection pool to be used has not been released. So the solution is to find ways to make the event a Tomcat shutdown listener, and then manually release the database connection.

The Tomcat shutdown event listeners

Very simple example of realization of a ServletContextListener, and you can register to web.xml.

public class ShutdownListener implements ServletContextListener  {
 
	private static Logger logger = Logger.getLogger(ShutdownListener.class);
 
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		logger.info("contextDestroyed");
		logger.info("DBPool shutdown start...");
		try {
			DBPool.clear();
			DBPool.close();
		} catch (Throwable e) {
			logger.fatal("", e);
		}
		logger.info("DBPool shutdown done");
	}
 
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		logger.info("contextInitialized");
	}
 
}
<listener>
    <listener-class>xxx.xxx.xxx.ShutdownListener</listener-class>
</listener>

Close and release the database connection pool

Tag does not use a complex database connection pool, with org.apache.commons.pool.impl.GenericObjectPooland org.apache.commons.pool.BasePoolableObjectFactorya combination of.

In contextDestroyed method of ServletContextListener

  1. Execution GenericObjectPool.clear (), the pool is cached object destroyed
  2. Execution GenericObjectPool.close (), close the object pool, is no longer supported borrowObject (), but still support returnObject () method and return immediately after the destruction of the object

After finish these two steps, the shutdown script execution Tomcat, Tomcat process a few seconds will automatically shut down.

 
The Categories: the Java Tags:

Guess you like

Origin www.cnblogs.com/zhoading/p/11730056.html