在前面的博文中我们介绍了创建Druid连接的线程的逻辑《6-DruidDataSource物理连接创建线程createAndStartCreatorThread》 ,这里来看下销毁连接的逻辑。
这个代码调用逻辑是来源于前面说的DruidDataSource的连接对象获取时的初始化方法init
调用代码如下:
createAndStartDestroyThread();
直接来看DruidDataSource类型的createAndStartDestroyThread代码如下所示:
protected void createAndStartDestroyThread() {
//创建销毁任务
destroyTask = new DestroyTask();
//这里我们没有配置销毁定时器
if (destroyScheduler != null) {
long period = timeBetweenEvictionRunsMillis;
if (period <= 0) {
period = 1000;
}
destroySchedulerFuture = destroyScheduler.scheduleAtFixedRate(destroyTask, period, period,
TimeUnit.MILLISECONDS);
initedLatch.countDown();
return;
}
String threadName = "Druid-ConnectionPool-Destroy-" + System.identityHashCode(this);
//创建与启动销毁线程
destroyConnectionThread = new DestroyConnectionThread(threadName);
destroyConnectionThread.start();
}
这里直接来看代码了
public class DestroyConnectionThread extends Thread {
public DestroyConnectionThread(String name) {
super(name);
this.setDaemon(true);
}
public void run() {
initedLatch.countDown();
for (; ; ) {
// 从前面开始删除
try {
if (closed || closing) {
break;
}
if (timeBetweenEvictionRunsMillis > 0) {
Thread.sleep(timeBetweenEvictionRunsMillis);
} else {
Thread.sleep(1000); //
}
if (Thread.interrupted()) {
break;
}
destroyTask.run();
} catch (InterruptedException e) {
break;
}
}
}
}
看下销毁任务的代码:
public class DestroyTask implements Runnable {
public DestroyTask() {
}
@Override
public void run() {
shrink(true, keepAlive);
if (isRemoveAbandoned()) {
removeAbandoned();
}
}
}