简体   繁体   中英

Close database connection in connection pool

I am using JDBC connection pool to make connection with mysql server.

Below is my code snippet

  try {
       InitialContext initialContext = new InitialContext();
        Context context = (Context) initialContext.lookup("java:comp/env"); 
        DataSource ds = (DataSource) context.lookup("connpool");
        Connection conn =  ds.getConnection();
        //some query is executed 
    }
    catch(SQLException ex)
   {   } 
   finally {  conn.close(); }

My Doubt:

My doubt here is even I am making connection close(conn.close()), in MySQL show processlist command it showing connection.

If I send more requests to servlet the connections count in show processlist is also increasing,

When this connection will be closed.

Why I am afraid means it it reached max connections count it will show error.

My Connection pool configuration is:

          <Resource name="connpool" auth="Container" 
             type="javax.sql.DataSource" 
             maxActive="1" maxIdle="0"
             maxWait="-1"
             username="xxxxx" 
             password="xxxxx"
             driverClassName="com.mysql.jdbc.Driver"
             url="jdbc:mysql://localhost:3306/govsocial"/>

From tomcat documentation , there are initial values that are not set consistently with what you are setting in the resource config.

  • minIdle (default is 10)
  • initialSize (default is 10)

If you have a look at the code for init() method , with the above defaults and your configuration with

  • maxActive = "1"
  • maxIdle = "0"

You will end up with:

  • maxActive = "1"
  • maxIdle = "1"
  • minIdle = "1"
  • initialSize = "1"

This is a pool of 1 connection, and the purpose of the pool is to keep some (depending on config) connections open for incoming requests. Calling close() will only pass the connection from the busy queue to the idle one.

If you really want no pool at all, you should try setting explicitly:

  • maxActive = "1"
  • maxIdle = "0"
  • minIdle = "0"
  • initialSize = "0"

Note that maxWait = -1 means a new connection will wait until a connection is available - without timeout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM