Prevent Tomcat C3p0 memory leaks

Create a class:

public class RemoveTomcatC3P0Connections implements ServletContextListener {

	private static final Logger LOGGER = LoggerFactory.getLogger(RemoveTomcatC3P0Connections.class);

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		// TODO Auto-generated method stub

	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// This manually deregisters JDBC driver, which prevents Tomcat 7 from complaining about memory leaks wrto this class
		Enumeration<Driver> drivers = DriverManager.getDrivers();
		while (drivers.hasMoreElements()) {
			Driver driver = drivers.nextElement();
			try {
				DriverManager.deregisterDriver(driver);
				LOGGER.info(String.format("deregistering jdbc driver: %s", driver));
			} catch (SQLException e) {
				LOGGER.info(String.format("Error deregistering driver %s", driver), e);
			}

		}

		XmlWebApplicationContext xmlWebApplicationContext = (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
		if(xmlWebApplicationContext == null) {
			LOGGER.info("No se ha podido recuperar el contexto de Spring por segunda vez");
		}else if(xmlWebApplicationContext != null) {
			try {
				com.mchange.v2.c3p0.ComboPooledDataSource pool = (com.mchange.v2.c3p0.ComboPooledDataSource) xmlWebApplicationContext.getBean("dataSource");
				LOGGER.info("Se procede a cerrar las conexiones de la url: " + pool.getJdbcUrl());
				pool.close(true);
				LOGGER.info("Se cierra la conexion con el Pool de C3P0");
			} catch (Exception e) {
				LOGGER.info("Error al cerrar la conexion con el Pool de C3P0", e);
			}
		}

	}

}

Add to web.xml:

	<listener> 
		<listener-class> 
			mi.paquete.RemoveTomcatC3P0Connections
		</listener-class>
	</listener>

log:

15:36:28.051 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] INFO  e.t.a.p.r.c.RemoveTomcatC3P0Connections - deregistering jdbc driver: sun.jdbc.odbc.JdbcOdbcDriver@4fda99
15:36:28.051 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] INFO  e.t.a.p.r.c.RemoveTomcatC3P0Connections - deregistering jdbc driver: oracle.jdbc.OracleDriver@2d405a
15:36:28.051 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] INFO  e.t.a.p.r.c.RemoveTomcatC3P0Connections - deregistering jdbc driver: net.sf.log4jdbc.DriverSpy@f72dd7
16:21:26.880 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] INFO  e.t.a.p.r.c.RemoveTomcatC3P0Connections - Se procede a cerrar las conexiones de la url: jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.3.2.44) (PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)))

Be carefull with net.sf.log4jdbc.Log4jdbcProxyDataSource, it´s a wrapper for log not a Data Source.

Anuncios
Prevent Tomcat C3p0 memory leaks