上一篇分析了创建连接线程,今天来看下销毁连接线程。
1. 2种方式执行 destroyTask 中封装的逻辑
分2种情况,取决于使用者有没有在初始化连接池前设置 destroyScheduler:
protected void createAndStartDestroyThread() {
// 这里创建真正销毁连接的任务
destroyTask = new DestroyTask();
// 如果在初始化连接池之前设置了销毁连接的定时执行器 destroyScheduler,就进入
if (destroyScheduler != null) {
long period = timeBetweenEvictionRunsMillis;
if (period <= 0) {
period = 1000;
}
// 以 timeBetweenEvictionRunsMillis 为执行周期,执行销毁连接任务
destroySchedulerFuture = destroyScheduler.scheduleAtFixedRate(destroyTask, period, period,
TimeUnit.MILLISECONDS);
initedLatch.countDown();
return;
}
// 如果没有设置 destroyScheduler,则创建 DestroyConnectionThread
String threadName = "Druid-ConnectionPool-Destroy-" + System.identityHashCode(this);
destroyConnectionThread = new DestroyConnectionThread(threadName);
destroyConnectionThread.start();
}
我们先看第2种情况,创建的 DestroyConnectionThread 里面的逻辑:
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;
}
}
}
可以看到,使用了 Sleep 的方式,定时执行 destroyTask 中封装的逻辑;而第1种使用的线程池定时执行 destroyTask 中封装的逻辑。

本文详细解析了Druid连接池中销毁连接线程的两种执行策略:使用线程池定时执行和自定义DestroyConnectionThread。作者介绍了每种方法的工作原理,并重点展示了shrink方法中封装的销毁逻辑,包括空闲时间判断和连接处理过程。
最低0.47元/天 解锁文章
281

被折叠的 条评论
为什么被折叠?



