Search code examples
javaconnection-poolingapache-commons-dbcp

Java DBCP2 Connection pooling is creating connection agian after max connection closed


I am attempting to use connection pooling using apache dbcp2.

My maxTotal connection is 5. I am closing every connection after it is used.

But still i am getting connection after 5 connection closed from connection pool.

whetehr it will ping database to get connection after 5 connections are closed ? or it will get from connection pool itself without going db.

Below is my sample code snippet. Please correct my understanding about connection pooling.

BasicDataSource bds = getBasicDataSource();

System.out.println (bds.getMaxTotal()); // Prints - 5

for (int i=0; i<10; i++) {
    conn = bds.getConnection();
    System.out.println("Conn "+conn); // conn object printing different values for all 10 connections
    conn.close();
}

Solution

  • The connection a client gets from a pool is not really a java.sql.Connection, it's a wrapper (a proxy) for a java.sql.Connection that customizes the behavior of some methods. The close() method is one of them and does not close the Connection instance but returns it to the pool.

    Try to use C3PO, from my point of view it is better than DBCP.