Java – Tomcat JDBC connection pool (releasing connection)

connection-poolingjavajdbctomcat7

Referring to Tomcat JBDC connection pool, I see in the standalone java example given there, one gets the connection using datasource.getConnection()which is cool. But in the finally block, it says con.close().

Question: When I implement this, it seems obvious that the con I get from datasource will be closed every time in the finally. When this is closed, will the connection pooling mechanism acquire a new connection and adds it to the pool?

I presume there should be a method call like releaseConnection() that will let the pool take its own decision whether to close it or let it be open for some other use.

I've also tried doing this ConnectionPool aPool = datasource.createPool();
But I see there is nothing like release connection on this aPool.

I think I'm missing something here?
Appreciate your help.

Code snippet from Tomcat JBDC connection pool:

            DataSource datasource = new DataSource();
            datasource.setPoolProperties(p); 

            Connection con = null;
            try {
              con = datasource.getConnection();
              Statement st = con.createStatement();
              ResultSet rs = st.executeQuery("select * from user");
              int cnt = 1;
              while (rs.next()) {
                  System.out.println((cnt++)+". Host:" +rs.getString("Host")+
                    " User:"+rs.getString("User")+" Password:"+rs.getString("Password"));
              }
              rs.close();
              st.close();
            } finally {
              if (con!=null) try {con.close();}catch (Exception ignore) {}
            }

Best Answer

Since you call the close() on a method obtained by the pool it is up to the pool what to do inside this method call. It does not neccessarily have to close the pooled database connection - it may do some cleanup and then add the connetion back to the pool.

This is already answered in Closing JDBC Connections in Pool

Related Topic