二、得到和返回连接
DBConnectionManager提供getConnection()方法和freeConnection方法,这些方法有客户程序使用。所有的方法以连接池名字所参数,并调用特定的连接池对象。
public Connection getConnection(String name) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null) {
return pool.getConnection();
}
return null;
}
public Connection getConnection(String name, long time) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null) {
return pool.getConnection(time);
}
return null;
}
public void freeConnection(String name, Connection con) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null) {
pool.freeConnection(con);
}
}
三、关闭
最后,由一个release()方法,用来完好地关闭连接池。每个DBConnectionManager客户必须调用getInstance()方法引用。有一个计数器跟踪客户的数量。方法release()在客户关闭时调用,技术器减1。当最后一个客户释放,DBConnectionManager关闭所有的连接池。
List 11-14
public synchronized void release() {
// Wait until called by the last client
if (--clients != 0) {
return;
}
Enumeration allPools = pools.elements();
while (allPools.hasMoreElements()) {
DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();
pool.release();
}
Enumeration allDrivers = drivers.elements();
while (allDrivers.hasMoreElements()) {
Driver driver = (Driver) allDrivers.nextElement();
try {
DriverManager.deregisterDriver(driver);
log("Deregistered JDBC driver " + driver.getClass().getName());
}
catch (SQLException e) {
log(e, "Can not deregister JDBC driver: " +
driver.getClass().getName());
}
}
}
当所有连接池关闭,所有jdbc驱动程序也被注销。
查看本文来源