Koray Tugay
Koray Tugay

Reputation: 23780

Tomcat warns me about memory leak even though mysql connector is in lib folder

I know there are a few questions about this and the answer seems to put the Driver in the lib folder of the Tomcat. However I am still getting a warning. Why might this be?

Here is my pom.xml:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.35</version>
    <scope>provided</scope>
</dependency>

and in my Tomcat\lib folder I have:

Korays-MacBook-Pro:apache-tomcat-8.0.23 koraytugay$ ls lib/mysql-connector-java-5.1.35-bin.jar 
lib/mysql-connector-java-5.1.35-bin.jar

This is the only method I have that makes a db connection:

import java.sql.*;

public class TicketDAO {
    public static void insertTicketToDB(String name)
            throws ClassNotFoundException, SQLException,
            IllegalAccessException, InstantiationException {
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "ticketsdb";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "";
        String password = "";
        Class.forName(driver).newInstance();
        Connection conn = DriverManager.getConnection(url + dbName, userName, password);
        String insertTableSQL = "INSERT INTO ticket(name) VALUES(?)";
        PreparedStatement preparedStatement = conn.prepareStatement(insertTableSQL);
        preparedStatement.setString(1, name);
        preparedStatement.executeUpdate();
        conn.close();
    }
}

When I shutdown Tomcat I will see:

23-Jun-2015 14:31:12.693 WARNING [localhost-startStop-2] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [ROOT] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. 

This is very likely to create a memory leak. Stack trace of thread:

What is it that I am doing wrong?

Upvotes: 0

Views: 868

Answers (1)

alexanoid
alexanoid

Reputation: 25780

Memory leaks manifests due to MySQL's 'Abandonded connection cleanup thread'. This thread starts with the first request and holds a reference to the webapp's classloader. With classesToInitialize you can prevent this memory leak too.

To prevent this particular memory leak you should edit your tomcat/conf/server.xml and change

<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />

to

<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" classesToInitialize="com.mysql.jdbc.NonRegisteringDriver" />

Upvotes: 2

Related Questions