📄 poolconnectionmanager.java
字号:
package ATMSystemServer.SqlConnection;
import java.sql.*;
import java.util.*;
/*
* 操作和管理连接容器
* */
public class PoolConnectionManager {
protected LinkedList listCon = new LinkedList();// 一个存放链接池的链表
//数据库的url
protected String DBUrl = null;
//数据库用户名
protected String DBUser = null;
//数据库的用户密码
protected String DBPasswd = null;
/*最大连接数*/
protected int nMaxCon = 0;
/*连接最大使用时间*/
protected int nMaxUsedTime =0;
/*当前已用连接数*/
protected int nConNum = 0;
/*
* 构造函数
* */
public PoolConnectionManager(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;
}
/*从连接池中取得连接(线程安全函数)
* 返回的数据库连接容器
* */
synchronized public PoolConnection get()
{
if (listCon.size() > 0)
{
//有连接时,直接取得连接
return (PoolConnection) listCon.removeFirst();
}
if (nConNum < nMaxCon)
{
//如果没有多余连接,但连接池未满,新建一个连接
return createCon();
}
return null;
}
/*
* 销毁连接
* */
synchronized public void release(PoolConnection pcon)
{
pcon.UsedTimesAdd();
if (pcon.getUsedTimes() > nMaxUsedTime)
{
//如果使用时间大于最大使用时间,则该连接被回收
try
{
nConNum--;
pcon.con.close();
}
catch (Exception e)
{
System.err.println("Fail to close DB Con");
}
}
else
{
//否则,该连接被重新分配
listCon.add(pcon);
}
}
/*建立连接容器*/
protected PoolConnection createCon()
{
PoolConnection pcon = new PoolConnection();
try {
pcon.con = DriverManager.getConnection(DBUrl, DBUser, DBPasswd);
pcon.con.setAutoCommit(true);
nConNum++;
} catch (Exception e)
{
e.printStackTrace();
System.err.println("Fail to create DB Con");
}
return pcon;
}
/*回收器
* 将连接池中的所有连接关闭
*/
protected void finalize() {
try {
while (listCon.size() > 0) {
PoolConnection pCon = (PoolConnection) listCon.removeFirst();
pCon.con.close();
}
} catch (Exception e) {
//
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -