/** * 治理類DBConnectionManager支持對一個或多個由屬性文件定義的數據庫連接 * 池的訪問.客戶程序可以調用getInstance()方法訪問本類的唯一實例. */ public class ConnectPool { static public ConnectPool instance; // 唯一實例 static public int clients; public Vector drivers = new Vector(); //驅動 public PRintWriter log; public Hashtable pools = new Hashtable(); //連接
/** * 返回唯一實例.假如是第一次調用此方法,則創建實例 * * @return DBConnectionManager 唯一實例 */ static synchronized public ConnectPool getInstance() { if (instance == null) { instance = new ConnectPool(); }
clients++;
return instance; }
/** * 建構函數私有以防止其它對象創建本類實例 */ public ConnectPool() { init(); }
/** * 將連接對象返回給由名字指定的連接池 * * @param name 在屬性文件中定義的連接池名字 * @param con 連接對象 */ public void freeConnection(String name, Connection con) { DBConnectionPool pool = (DBConnectionPool) pools.get(name); if (pool != null) { pool.freeConnection(con); } else { System.out.println("pool ==null"); } clients--; }
/** * 獲得一個可用的(空閑的)連接.假如沒有可用連接,且已有連接數小于最大連接數 * 限制,則創建并返回新連接 * * @param name 在屬性文件中定義的連接池名字 * @return Connection 可用連接或null */ public Connection getConnection(String name) { DBConnectionPool pool = (DBConnectionPool) pools.get(name); if (pool != null) { //return pool.getConnection(); return pool.returnConnection(); } return null; }
/** * 獲得一個可用連接.若沒有可用連接,且已有連接數小于最大連接數限制, * 則創建并返回新連接.否則,在指定的時間內等待其它線程釋放連接. * * @param name 連接池名字 * @param time 以毫秒計的等待時間 * @return Connection 可用連接或null */ public Connection getConnection(String name, long time) { DBConnectionPool pool = (DBConnectionPool) pools.get(name); if (pool != null) { return pool.getConnection(time); } return null; }
/** * 關閉所有連接,撤銷驅動程序的注冊 */ public synchronized void release() { // 等待直到最后一個客戶程序調用 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);