nfvindaloo
nfvindaloo

Reputation: 938

Spring Tomcat permgen issue

Hi I'm getting a permgen error on tomcat (and on glassfish) from my application, and i understand they are caused by the ClassLoader hanging on to references between hot-deploys.

Id like to track down the memory leak but have not done it before, I think a good star would be fixing the following issues which tomcat spits out when i re-deploy:

SEVERE: The web application [] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
06-Jan-2013 19:47:08 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [] appears to have started a thread named [Resource Destroyer in BasicResourcePool.close()] but has failed to stop it. This is very likely to create a memory leak.

I guess i need to kill these threads inside some spring destroy handler, bud Im not sure how i would find the handles to destroy them?

Cheers! NFV

Upvotes: 1

Views: 2265

Answers (1)

Marcel Stör
Marcel Stör

Reputation: 23565

We use a ServletContextListener to unregister JDBC drivers.

web.xml

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
...
  <listener>
    <listener-class>ShutdownListener</listener-class>
  </listener>

ShutdownListener

public class ShutdownListener implements ServletContextListener {
  private final Logger logger = LoggerFactory.getLogger(ShutdownListener.class);

  @Override
  public void contextInitialized(ServletContextEvent sce) {
    logger.info("Context initialized.");
  }

  @Override
  public void contextDestroyed(ServletContextEvent sce) {
    deregisterJdbcDrivers();
    // more clean-up tasks here
  }

  private void deregisterJdbcDrivers() {
    final Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
      final Driver driver = drivers.nextElement();
      if (this.getClass().getClassLoader().equals(getClass().getClassLoader())) {
        try {
          DriverManager.deregisterDriver(driver);
          logger.info("Deregistered '{}' JDBC driver.", driver);
        } catch (SQLException e) {
          logger.warn("Failed to deregister '{}' JDBC driver.", driver);
        }
      }
    }
  }
}

Upvotes: 3

Related Questions