|
一個連接容器,記錄連接和連接使用狀況
package db.khan;

import java.sql.*;

 /**//*數(shù)據(jù)庫連接容器
* */
 public class DBPoolCon {
 /**//*容器中的連接*/
public Connection con = null;

public int nUsedTimes = 0;

 DBPoolCon() {
}

 public Connection get() {
return con;
}
}一個操作和管理連接容器的連接池
package db.khan;

import java.sql.*;
import java.util.*;

 /** *//**連接池類
* */
 public class DBConPool {
protected LinkedList listCon = new LinkedList();// 一個存放鏈接池的鏈表
protected String DBUrl = null;
protected String DBUser = null;
protected String DBPasswd = null;
 /** *//**最大連接數(shù)*/
protected int nMaxCon = 0;
 /** *//**連接最大使用時間*/
protected int nMaxUsedTime = 0;
 /** *//**當前已用連接數(shù)*/
protected int nConNum = 0;

 /** *//**構(gòu)造器
* @param String DBUrl
* @param String DBUser
* @param String DBPasswd
* @param int nMaxCon
* @param int nMaxUsedTime*/
 DBConPool(String DBUrl, String DBUser, String DBPasswd, int nMaxCon, int nMaxUsedTime) {
this.DBUrl = DBUrl;
this.DBUser = DBUser;
this.DBPasswd = DBPasswd;

this.nMaxCon = nMaxCon;
this.nMaxUsedTime = nMaxUsedTime;
}

 /** *//**從連接池中取得連接(線程安全函數(shù))
* @return DBPoolCon 返回的數(shù)據(jù)庫連接容器
* */
 synchronized public DBPoolCon get() {
 if (listCon.size() > 0) {//有連接時,直接取得連接
return (DBPoolCon) listCon.removeFirst();
}
 if (nConNum < nMaxCon) {//如果沒有多余連接,但連接池未滿,新建一個連接
return createCon();
}
System.out.println("Fail to get DB con, too many con: " + nConNum + " max:" + nMaxCon);
return null;
}

 /** *//**銷毀連接
* @param DBPoolCon pCon*/
 synchronized public void release(DBPoolCon pCon) {
pCon.nUsedTimes++;
 if (pCon.nUsedTimes > nMaxUsedTime) {//如果使用時間大于最大使用時間,則該連接被回收
 try {
nConNum--;
pCon.con.close();
System.out.println("DB Con closed for used out");
 } catch (Exception e) {
System.err.println("Fail to close DB Con");
}
 } else { //否則,該連接被重新分配
listCon.add(pCon);
}
}

 /** *//**建立連接容器
* @return DBPoolCon 返回一個連接容器*/
 protected DBPoolCon createCon() {
DBPoolCon pCon = new DBPoolCon();
 try {
pCon.con = DriverManager.getConnection(DBUrl, DBUser, DBPasswd);
pCon.con.setAutoCommit(true);
nConNum++;
System.out.println("DB Con created, con num:" + nConNum + " max:" + nMaxCon);
 } catch (Exception e) {
System.err.println("Fail to create DB Con");
}
return pCon;
}

 /** *//**回收器
* 將連接池中的所有連接關(guān)閉*/
 protected void finalize() {
 try {
 while (listCon.size() > 0) {
DBPoolCon pCon = (DBPoolCon) listCon.removeFirst();
pCon.con.close();
}
 } catch (Exception e) {
System.err.println("Fail to close DB Con");
}
}
}
|