DruidDataSource类源码分析(六)

createAndStartDestroyThread( )

两种回收连接池的策略:

  1. 通过作DestroyConnectionThread
  2. 按timeBetweenEvictionRunsMillis间隔调度执行destoryTask
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();
}

DestroyTask

  1. shrink(true) 主要根据配置参数判断线程池中连接的空闲时间idleMillis 是否大于等于 minEvictableIdleTimeMillis,如果是则关闭该连接。

  2. removeAbandoned()方法主要是在配置连接泄露处理策略时,关闭泄露的连接

public class DestroyTask implements Runnable {
    public DestroyTask() {

    }

    @Override
    public void run() {
        shrink(true, keepAlive);

        if (isRemoveAbandoned()) {
            removeAbandoned();
        }
    }

}

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
            destroyTask.run();
        } catch (InterruptedException e) {
            break;
        }
    }
}

你可能感兴趣的:(数据库)