Druid-代码段-4-1

所属文章:池化技术(一)Druid是如何管理数据库连接的?

 本代码段对应主流程4,丢弃连接的守护线程:


//连接池瘦身,参考主流程4
    public class DestroyConnectionThread extends Thread {

        public DestroyConnectionThread(String name){
            super(name); //给线程重命名
            this.setDaemon(true); //标记为守护线程
        }

        //run方法
        public void run() {
            initedLatch.countDown(); //通知init(主流程2)自己已经启动成功

            for (;;) { //死循环
                // 从前面开始删除
                try {
                    if (closed) {
                        break;
                    }

                    if (timeBetweenEvictionRunsMillis > 0) { //检查时间间隔,不启用(小于等于0时)则默认1s,事实上,druid对于该参数的缺省值是60s
                        Thread.sleep(timeBetweenEvictionRunsMillis);
                    } else {
                        Thread.sleep(1000); //默认1s
                    }

                    if (Thread.interrupted()) {
                        break;
                    }

                    destroyTask.run(); //启动destroy的run方法(在下方)
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

    }

    //DruidDataSource内部类
    public class DestroyTask implements Runnable {
        public DestroyTask() {

        }

        @Override
        public void run() {
            shrink(true, keepAlive); //连接池的检查&瘦身

            if (isRemoveAbandoned()) { //如果开启该属性,则进行强制回收检查
                removeAbandoned();
            }
        }

    }

你可能感兴趣的:(Druid-代码段-4-1)