Prevent Memory Leak by De-Registering JDBC Driver
It is observed in SpringBoot Application that Database Connections might cause memory leaks.
Although Tomcat forcibly deregisters the JDBC drivers, it is good practice to clean up the resources created by webapps on context destruction. It will ensure memory leak prevention that Tomcat at times does not ensure.
In simple words, it means if somehow, JDBC driver does not automatically deregister when the servlet context is being destroyed, it can be done at the container level also.
Below snippet will ensure that the deregister of Drivers happen at the time of context destruction.
@Bean
protected ServletContextListener listener() {
return new ServletContextListener() {
@Override
public void contextInitialized(ServletContextEvent sce) {
}
@Override
public final void contextDestroyed(ServletContextEvent sce) {
// ... First close any background tasks which may be using the DB ...
// ... Then close any DB connection pools ...
// Now deregister JDBC drivers in this context's ClassLoader:
// Get the webapp's ClassLoader
ClassLoader cl = Thread.currentThread().getContextClassLoader();
// Loop through all drivers
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver driver = drivers.nextElement();
if (driver.getClass().getClassLoader() == cl) {
// This driver was registered by the webapp's ClassLoader, so deregister it:
try {
System.out.println("Deregistering JDBC driver {}" + driver);
DriverManager.deregisterDriver(driver);
} catch (SQLException ex) {
System.out.println("Error deregistering JDBC driver {}" + ex);
}
} else {
// driver was not registered by the webapp's ClassLoader and may be in use elsewhere
System.out.println("Not deregistering JDBC driver {} as it does not belong to this webapp's ClassLoader" + driver);
}
}
}
};
}
If any issues are encountered, do mention the same in comments section.I will be happy to help.######### Happy Coding #########
Comments
Post a Comment