Atma
Atma

Reputation: 29775

Does closing a connection pool in a REST service defeat the purpose of a connection pool in the first place?

I'm using BoneCP for connection pooling jdbc connections to my mysql database. I'm using the bonecp example in my REST application.

If every REST request is opening and closing the connection pool, doesn't this defeat the point of connection pooling in the first place?

Here is the code:

 public class ExampleJDBC {

/** Start test
 * @param args none expected.
 */
public static void main(String[] args) {
    BoneCP connectionPool = null;
    Connection connection = null;

    try {
        // load the database driver (make sure this is in your classpath!)
        Class.forName("org.hsqldb.jdbcDriver");
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

    try {
        // setup the connection pool
        BoneCPConfig config = new BoneCPConfig();
        config.setJdbcUrl("jdbc:hsqldb:mem:test"); // jdbc url specific to your database, eg jdbc:mysql://127.0.0.1/yourdb
        config.setUsername("sa"); 
        config.setPassword("");
        config.setMinConnectionsPerPartition(5);
        config.setMaxConnectionsPerPartition(10);
        config.setPartitionCount(1);
        connectionPool = new BoneCP(config); // setup the connection pool

        connection = connectionPool.getConnection(); // fetch a connection

        if (connection != null){
            System.out.println("Connection successful!");
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT 1 FROM      INFORMATION_SCHEMA.SYSTEM_USERS"); // do something with the connection.
            while(rs.next()){
                System.out.println(rs.getString(1)); // should print out "1"'
            }
        }
        connectionPool.shutdown(); // shutdown connection pool.
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
} 
 }

Upvotes: 0

Views: 306

Answers (1)

Daniel Pittman
Daniel Pittman

Reputation: 17212

Yes, it would defeat the purpose to open or close the connection pool more than once in the (typical) lifecycle of your application. You should fetch a connection from the pre-established pool each time instead.

Upvotes: 2

Related Questions