Properties:
- When cost of creating an object from scratch is high it might be a good idea to reuse already created objects.
- Identified by a pool class that objects are retrieved from and then released back to.
Implementation:
- Reused objects might be wrapped by another object.
- Pool class keeps created objects.
- Client requests a new object instance from pool when it needs a new object. After client is done with object instance it releases the object, so that the object can be reused again.
Java Example Usage:
- com.mchange.v2.c3p0.ComboPooledDataSource
Example Usage:
// create connection pool
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass( "org.mysql.Driver" );
dataSource.setJdbcUrl( "jdbc:mysql://localhost/testdb" );
dataSource.setUser("user");
dataSource.setPassword("password");
dataSource.setMinPoolSize(5);
dataSource.setAcquireIncrement(5);
dataSource.setMaxPoolSize(20);
Connection conn = null;
Statement stmt = null;
ResultSet resultSet = null;
try {
conn = dataSource.getConnection();// get a connection from pool
stmt = conn.createStatement();
resultSet = stmt.executeQuery("SELECT * FROM Person");
int numcols = resultSet.getMetaData().getColumnCount();
while(resultSet.next()) {
for(int i=1;i<=numcols;i++) {
System.out.print(resultSet.getString(i));
}
}
} catch(SQLException e) {
e.printStackTrace();
} finally {
try { if (resultSet != null) resultSet.close(); } catch(Exception e) { }
try { if (stmt != null) stmt.close(); } catch(Exception e) { }
try { if (conn != null) conn.close(); } catch(Exception e) { } // Release connection back to pool
}
Comments
Post a Comment