}
// connectionToRelease.setAvailable(true);
available.add(connectionToRelease);
poolLock.notify();
//log
}
} /** 使用线程来创建连接,创建完成通知线程等待新的连接 */
public void run(){
try {
// Connection connection = makeNewConnection();
synchronized(this) {
// this.availableConnections.addElement(connection);
// this.connectionUsageTimes.addElement(new java.util.Date());
// this.connectionPending = false;
notifyAll();
}
} catch(Exception e) {
// SQLException or OutOfMemory
//放弃新的连接和等待已在连接释放
}
} /**
* 创建新的连接到数据源
* @return Connection 返回最新连接实例或NULL(连接数超过最大数)
* @throws Exception 创建连接出错时抛出
*/
protected synchronized Connection createNewConnection()
throws Exception {
Connection oneConnection = null;
//检查当前池中连接数,连接数不允许超过最大连接数
int total = 0;
int avail = 0;
int inuse = 0;
boolean isFirstConnection = false; synchronized (poolLock) {
avail = available.size();
inuse = inUse.size();
total = avail + inuse;
isFirstConnection = (total == 0); //如果有可用的连接,不去创建连接,直接使用即可
if (avail > 0)
return null;
//超出连接池最大连接数
if (total > this.maxPoolSize)
return null;
} if (true)
System.out.println("创建新连接总连接数:" + total +
"正在使用的连接数: " + inuse +
"可以使用的连接数: " + avail +
"连接名称: "); //this.getDataContext());
try {
Class.forName(this.dbDriver);
oneConnection = DriverManager.getConnection(this.dbURL, this.dbLogin,
this.dbPassword);
}
catch (Exception ex) {
throw new Exception("创建连接时出错:", ex);
} synchronized (poolLock) {
int totalPools = available.size() + inUse.size();
if (totalPools >= this.maxPoolSize) {
// oneConnection.disconnect();
//log.warn("产生太多连接对象...取消一个:inUse.size()=" + inUse.size() +
// " available.size()=" + available.size());
return null;
}
else {
// oneConnection.setAvailable(false);
inUse.put("xx", oneConnection);
}
} if (true) {
System.out.println("新连接 " + // oneConnection.getId() +
" 已成功创建. " + "现有 " + avail +
" 个连接对象可用。 '" + //getDataContext() +
"', " + inuse + " 个正被使用。");
}
if (isFirstConnection) {
initialized = true;
// supportsTransactions = oneConnection.supportsTransactions();
// JDBCConfig myConfig = this.getJDBCConfig(getDataContext());
} return oneConnection;
} /**
* 从可用列表中清空可用的连接
* @throws Exception 当清空操作出错时抛出
*/
protected void cleanAvailable() throws Exception {
//if (log.isDebugEnabled()) {
// log.debug("检查可用连接池来清空连接。");
//} long startTime = System.currentTimeMillis();
boolean removedConnections = false;
synchronized (poolLock) {
for (int i = 0; i < available.size();) {
Connection dbc = (Connection) available.get(i);
if (!isValidConnection(dbc)) {
//dbc.disConnect();
available.remove(i);
removedConnections = true;
} else {
i++;
}
} if (removedConnections) poolLock.notify();
}
} /**
* 清空连接池-
* @throws Exception
* @throws Exception
*/
public void clean() throws Exception, Exception {
//if (log.isDebugEnabled()) {
// log.debug("检测连接池陈旧的连接。");
//} long now = System.currentTimeMillis();
long lastTouched = 0;
Connection conn = null;
ArrayList connToRelease = null; /* 使用矢量来保存连接标识 */
List connectionsToBeRemoved = new ArrayList();
/* 保存连接对象是否应该被删除 */
boolean bCheckToRemove = false;
} /**
* 连接库连接池是否已初始化
* @return boolean
*/
public boolean isInitialized() {
return initialized;
} /**
* 检查数据连接池是否已满
* @return boolean
*/
protected boolean isFull() {
int inuse, avail;
synchronized (poolLock) {
inuse = inUse.size();
avail = available.size();
}
/*if (log.isDebugEnabled()) {
int totalConnections = avail + inuse;
log.debug("可用连接数:" + avail +
"正用连接数: " + inuse +
"连接总数: " + totalConnections);
}*/ return (inuse >= maxPoolSize);
} /**
* 通过简单SQL语句来验证连接是否可用
* @param conn Connection数据库连接对象
* @return boolean
*/
private boolean isValidConnection(Connection conn) {
PreparedStatement stmnt = null;
ResultSet rs=null;
try {
stmnt = conn.prepareStatement("select count(1)");
rs = stmnt.executeQuery();
rs.close();
rs=null;
stmnt.close();
stmnt=null;
return true;
} catch (SQLException se) {
Date currentTime = new Date();
//if (log.isDebugEnabled())
// log.info("发现非法连接 @ "+currentTime.toString());
try {
//连接被中断,所以不管是否关闭都要试图关闭它,也关闭rs与stmnt
conn.close();
} catch (Exception ex) {
}
return false;
}
} /**
* 返回连接数据库名/键值
* @return String
*/
public String getDBName() {
return dbName;
} /**
* 以ArrayList对象返回连接池中全部连接对象
* @return ArrayList对象包含数据库连接对象
* @throws Exception 若连接池没有返回时抛出
*/
public synchronized ArrayList getPoolList() throws Exception {
ArrayList al;
synchronized (poolLock) {
al = new ArrayList(available);
for (Iterator it = inUse.values().iterator(); it.hasNext();) {
al.add(it.next());
}
} return al;
} /**
* 返回数据库连接池潜在最大连接数
* @return 最大连接数
*/
public int getMaxConnections() {
return maxPoolSize;
} /**
* 设置连接池的最大连接数
* @param newMax 新指定最大连接数
* @throws Exception 在设置数据时出错抛出
*/
public synchronized void setMaxConnections(int newMax)
throws Exception {
maxPoolSize = newMax;
} /**
* Set the current database name/config key
*
* @param newDBName The new dataContext to set for this connection pool
*
*/
protected synchronized void setDBName(String newDBName) {
if (newDBName.equals("")) {
newDBName = DEFAULT_DB_CONTEXT_NAME;
} dbName = newDBName;
} public String toString() {
StringBuffer str = new StringBuffer();
str.append("数据连接池统计数据:\r\n");
str.append("正在使用的连接数:" + inUse);
str.append("可以使用的连接数:" + available); return str.toString();
}
public void setdbDriver(String var){
this.dbDriver=var;
}
public void setdbURL (String var){
this.dbURL=var;
}
public void setdbLogin (String var){
this.dbLogin=var;
}
public void setdbPassword(String var){
this.dbPassword=var;
}
}
// connectionToRelease.setAvailable(true);
available.add(connectionToRelease);
poolLock.notify();
//log
}
} /** 使用线程来创建连接,创建完成通知线程等待新的连接 */
public void run(){
try {
// Connection connection = makeNewConnection();
synchronized(this) {
// this.availableConnections.addElement(connection);
// this.connectionUsageTimes.addElement(new java.util.Date());
// this.connectionPending = false;
notifyAll();
}
} catch(Exception e) {
// SQLException or OutOfMemory
//放弃新的连接和等待已在连接释放
}
} /**
* 创建新的连接到数据源
* @return Connection 返回最新连接实例或NULL(连接数超过最大数)
* @throws Exception 创建连接出错时抛出
*/
protected synchronized Connection createNewConnection()
throws Exception {
Connection oneConnection = null;
//检查当前池中连接数,连接数不允许超过最大连接数
int total = 0;
int avail = 0;
int inuse = 0;
boolean isFirstConnection = false; synchronized (poolLock) {
avail = available.size();
inuse = inUse.size();
total = avail + inuse;
isFirstConnection = (total == 0); //如果有可用的连接,不去创建连接,直接使用即可
if (avail > 0)
return null;
//超出连接池最大连接数
if (total > this.maxPoolSize)
return null;
} if (true)
System.out.println("创建新连接总连接数:" + total +
"正在使用的连接数: " + inuse +
"可以使用的连接数: " + avail +
"连接名称: "); //this.getDataContext());
try {
Class.forName(this.dbDriver);
oneConnection = DriverManager.getConnection(this.dbURL, this.dbLogin,
this.dbPassword);
}
catch (Exception ex) {
throw new Exception("创建连接时出错:", ex);
} synchronized (poolLock) {
int totalPools = available.size() + inUse.size();
if (totalPools >= this.maxPoolSize) {
// oneConnection.disconnect();
//log.warn("产生太多连接对象...取消一个:inUse.size()=" + inUse.size() +
// " available.size()=" + available.size());
return null;
}
else {
// oneConnection.setAvailable(false);
inUse.put("xx", oneConnection);
}
} if (true) {
System.out.println("新连接 " + // oneConnection.getId() +
" 已成功创建. " + "现有 " + avail +
" 个连接对象可用。 '" + //getDataContext() +
"', " + inuse + " 个正被使用。");
}
if (isFirstConnection) {
initialized = true;
// supportsTransactions = oneConnection.supportsTransactions();
// JDBCConfig myConfig = this.getJDBCConfig(getDataContext());
} return oneConnection;
} /**
* 从可用列表中清空可用的连接
* @throws Exception 当清空操作出错时抛出
*/
protected void cleanAvailable() throws Exception {
//if (log.isDebugEnabled()) {
// log.debug("检查可用连接池来清空连接。");
//} long startTime = System.currentTimeMillis();
boolean removedConnections = false;
synchronized (poolLock) {
for (int i = 0; i < available.size();) {
Connection dbc = (Connection) available.get(i);
if (!isValidConnection(dbc)) {
//dbc.disConnect();
available.remove(i);
removedConnections = true;
} else {
i++;
}
} if (removedConnections) poolLock.notify();
}
} /**
* 清空连接池-
* @throws Exception
* @throws Exception
*/
public void clean() throws Exception, Exception {
//if (log.isDebugEnabled()) {
// log.debug("检测连接池陈旧的连接。");
//} long now = System.currentTimeMillis();
long lastTouched = 0;
Connection conn = null;
ArrayList connToRelease = null; /* 使用矢量来保存连接标识 */
List connectionsToBeRemoved = new ArrayList();
/* 保存连接对象是否应该被删除 */
boolean bCheckToRemove = false;
} /**
* 连接库连接池是否已初始化
* @return boolean
*/
public boolean isInitialized() {
return initialized;
} /**
* 检查数据连接池是否已满
* @return boolean
*/
protected boolean isFull() {
int inuse, avail;
synchronized (poolLock) {
inuse = inUse.size();
avail = available.size();
}
/*if (log.isDebugEnabled()) {
int totalConnections = avail + inuse;
log.debug("可用连接数:" + avail +
"正用连接数: " + inuse +
"连接总数: " + totalConnections);
}*/ return (inuse >= maxPoolSize);
} /**
* 通过简单SQL语句来验证连接是否可用
* @param conn Connection数据库连接对象
* @return boolean
*/
private boolean isValidConnection(Connection conn) {
PreparedStatement stmnt = null;
ResultSet rs=null;
try {
stmnt = conn.prepareStatement("select count(1)");
rs = stmnt.executeQuery();
rs.close();
rs=null;
stmnt.close();
stmnt=null;
return true;
} catch (SQLException se) {
Date currentTime = new Date();
//if (log.isDebugEnabled())
// log.info("发现非法连接 @ "+currentTime.toString());
try {
//连接被中断,所以不管是否关闭都要试图关闭它,也关闭rs与stmnt
conn.close();
} catch (Exception ex) {
}
return false;
}
} /**
* 返回连接数据库名/键值
* @return String
*/
public String getDBName() {
return dbName;
} /**
* 以ArrayList对象返回连接池中全部连接对象
* @return ArrayList对象包含数据库连接对象
* @throws Exception 若连接池没有返回时抛出
*/
public synchronized ArrayList getPoolList() throws Exception {
ArrayList al;
synchronized (poolLock) {
al = new ArrayList(available);
for (Iterator it = inUse.values().iterator(); it.hasNext();) {
al.add(it.next());
}
} return al;
} /**
* 返回数据库连接池潜在最大连接数
* @return 最大连接数
*/
public int getMaxConnections() {
return maxPoolSize;
} /**
* 设置连接池的最大连接数
* @param newMax 新指定最大连接数
* @throws Exception 在设置数据时出错抛出
*/
public synchronized void setMaxConnections(int newMax)
throws Exception {
maxPoolSize = newMax;
} /**
* Set the current database name/config key
*
* @param newDBName The new dataContext to set for this connection pool
*
*/
protected synchronized void setDBName(String newDBName) {
if (newDBName.equals("")) {
newDBName = DEFAULT_DB_CONTEXT_NAME;
} dbName = newDBName;
} public String toString() {
StringBuffer str = new StringBuffer();
str.append("数据连接池统计数据:\r\n");
str.append("正在使用的连接数:" + inUse);
str.append("可以使用的连接数:" + available); return str.toString();
}
public void setdbDriver(String var){
this.dbDriver=var;
}
public void setdbURL (String var){
this.dbURL=var;
}
public void setdbLogin (String var){
this.dbLogin=var;
}
public void setdbPassword(String var){
this.dbPassword=var;
}
}
直接用dbcp连接池嘛