Question

The code below doesn't appear to close MySQL connections properly even though we're closing resources in reverse order. When this code is run again, it seems to reuse the same MySQL process thread, which you can see below from looking at the MySQL process list cross-referenced with the actual MySQL queries run (pulled from mysql.general_log).

What are we doing wrong?

We're using Tomcat 6.0 (Don't ask. You don't want to know.) and Java 1.6.05.

Code:

String cat_name = request.getParameter("category");
if (cat_name != null) {
    DBWrapper db = new DBWrapper();
    ResultSet rs = null;
    try {     
      String parent_cat_name = null;      
      rs = db.executeQuery("SELECT cat_name FROM CATEGORY WHERE cat_code = (SELECT cat_main_code FROM category WHERE cat_name='" + cat_name + "')" );
      if (rs != null && rs.first()) {
        parent_cat_name = rs.getString("cat_name");
        page_title = title_prefix + parent_cat_name + " > " + cat_name;
      } else {
        page_title = title_prefix + cat_name;
      }
    } catch (Exception e) {
      System.out.println(e);
    } finally {
       try {
         if (rs != null) rs.close();
         if (db != null) db.closeConnection();
       } catch (Exception e) {
         System.out.println(e);     
       }
    }
}

DBWrapper.java:

    public class DBWrapper {
        private Connection con = null;
        private Statement stmt = null;
        private DataSource ds;
        private HashMap tables;

  public DBWrapper(){

        try {
            Context ctx = new InitialContext();
            if (ctx == null)
                throw new Exception("Boom - No Context");
            ds = (DataSource) ctx.lookup("java:comp/env/jdbc/eDB");
            if (ds != null) {
                con = ds.getConnection();
            }
            tables = new HashMap();
            loadMappings();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

        (other stuff)

        public void closeConnection(){
            try {
                if (stmt != null) stmt.close();
                if (con != null) con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

MySQL process list and queries:

http://imgur.com/69AzObj

Tomcat-database configuration:

Resource name="jdbc/eDB" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="***" password="****" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/ce?autoReconnect=true" /> 
Was it helpful?

Solution

Can you share the code from (other stuff)

How are you obtaining connection? from a db pool? We need to look at what is the concrete connection class to be able to help.

My theory is that your concrete connection class may not be releasing the connections properly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top