【Druid源码阅读】5. 创建并运行销毁连接线程:createAndStartDestroyThread()

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

上一篇分析了创建连接线程,今天来看下销毁连接线程。

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 中封装的逻辑。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值