Druid-源码实践实现数据源版本V0.1.1的多线程
-
实现init的时候开启一个守护销毁线程
-
实现守护销毁线程根据目前数据源连接数量大于最大连接数的时候放在销毁队列
init方法的时候创建守护线程
//池中的数量小于最小数量 创建连接
try{
if(poolingCount < minConnection){
for(int i=0;i<=minConnection-poolingCount;i++){
WmyPooledConnection wmyPooledConnection = new WmyPooledConnection(username, url, password, this);
freeConnection.add(wmyPooledConnection);
}
}
// 创建守护线程 监听
String threadName = "Druid-ConnectionPool-Destroy-" + System.identityHashCode(this);
destroyConnectionThread = new DestroyConnectionThread(threadName);
destroyConnectionThread.start();
}catch (SQLException e){
log.error("init datasource error, url: " + this.url, e);
}finally {
inited = true;
lock.unlock();
}
DestroyConnectionThread守护线程
public class DestroyConnectionThread extends Thread {
public DestroyConnectionThread(String name){
super(name);
this.setDaemon(true);
}
@Override
public void run() {
for (;;) {
// 从前面开始删除
try {
// 延续druid 的设计思路 等待间隔
if (timeBetweenEvictionRunsMillis > 0) {
//间隔等待
Thread.sleep(timeBetweenEvictionRunsMillis);
} else {
Thread.sleep(1000); // 默认
}
if (Thread.interrupted()) {
break;
}
//调用关闭方法
closeRun();
} catch (InterruptedException e) {
break;
}
}
}
}
closeRun方法
public void closeRun() {
try {
//获取锁
lock.lockInterruptibly();
} catch (InterruptedException e) {
return;
}
try {
if (!inited) {
//线程池没有初始化的话 直接返回
return;
}
//需要注销的连接
int killNum = 0;
if(runningConnection.size()>maxConnection){
killNum = maxConnection - runningConnection.size();
}
// 从正在运行的connect中获取需要销毁的线程
for(int i=0;i<killNum;i++){
killConnection.add(runningConnection.poll());
}
} finally {
lock.unlock();
}
try {
for(WmyPooledConnection connection : killConnection){
//判断当前的连接数量
if(connection.getConnectNum()==0){
//正在用这个连接池的数量为0的时候 kill
connection.close();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
总结
今天在实际去实现销毁连接的时候,会陷入怪圈,总感觉考虑的不够周全,总觉得要加一个这个限制,加一个那个限制导致过程中逻辑加上然后又删除修改。后来越做越乱,后面重新整理思路,应该基于上个版本实现版本V.0.1.1版本即可。后面在细化整理druid连接池的方案后一步步完善。