close() 歸還池中)。ConnectionFactory.bind() → ds.getConnection() → conn.close()。Serializable、equals/hashCode。InvocationHandler 實作,包裝真實連線,攔截關鍵方法:// 攔截邏輯精簡版
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
String name = m.getName();
if ("close".equals(name)) {
inUse = false; closeStatements(); return null; // 歸還池中
}
if ("createStatement".equals(name)) { stmtRef = (Statement) m.invoke(conn, args); return stmtRef; }
if ("prepareStatement".equals(name)) { pstmtRef = (PreparedStatement) m.invoke(conn, args); return pstmtRef; }
if (("commit".equals(name) || "rollback".equals(name)) && !supportsTx) return null;
return m.invoke(conn, args);
}
void reallyClose() throws SQLException { conn.close(); } // 池關閉時呼叫
Hashtable,提供 bind/lookup/rebind/unbind。建構子私有,靜態工廠方法初始化池參數、預建最小連線、啟動動態管理執行緒。javax.sql.DataSource,內部雙集合:FreeConnectionPool (LinkedHashSet)、BusyConnectionPool。核心邏輯:public synchronized Connection getFreeConnection() throws SQLException {
// 1. 從閒置池取出
// 2. 閒置池空則檢查是否可新建(未達上限)
// 3. 不可新建則從忙碌池尋找已歸還連線
// 4. 仍無則拋出異常
wrapper.inUse = true;
moveToBusy(wrapper);
return wrapper.getProxy();
}
public void schedule() { /* 動態管理:回收超時、補充閒置至最小值 */ }
public void close() { /* 關閉所有真實連線 */ }
schedule(),工廠關閉時自動結束。ConnectionParam param = new ConnectionParam(driver, url, user, pass);
ConnectionFactory cf = new ConnectionFactory(param, new FactoryParam(5, 2, 1)); // 動態管理
DataSource ds = ConnectionFactory.lookup("pool");
for (int i=0; i<10; i++) {
Connection c = ds.getConnection();
try { c.createStatement().executeQuery("SELECT 1"); }
finally { c.close(); } // 透明歸還
}
cf.unbind("pool"); // 關閉池
測試 10 次查詢:連線池 ~200ms vs 無池 ~1200ms(含驅動載入與連線建立),顯著降低延遲。
六個類別:_Connection、ConnectionFactory、ConnectionParam、FactoryManageThread、FactoryParam、testmypool,皆置於 scut.ailab.connectionpool 套件,完整原始碼已附於文末。