DruidCP源码阅读3 -- Druid连接池创建连接与销毁连接过程

在init过程中,会创建物理连接

接下来创建三个线程

// 创建三个线程
// 日志打印线程
createAndLogThread();
// 该线程负责创建连接线程 生产者生产线程
createAndStartCreatorThread();
// 销毁线程
createAndStartDestroyThread();

1、LogStatsThread线程 打印DruidDataSoource运行时的日志


        public LogStatsThread(String name) {
            super(name);
            this.setDaemon(true);
        }

        public void run() {
            try {
                for (; ; ) {
                    try {
                        logStats();
                    } catch (Exception e) {
                        LOG.error("logStats error", e);
                    }

                    Thread.sleep(timeBetweenLogStatsMillis);
                }
            } catch (InterruptedException e) {
                // skip
            }
        }
    }

2、创建守护线程connectionThread

CreateConnectionThread()方法是一个守护线程,用来生产连接线程,先了解几个成员变量

连接池中包含3部分:poolingCount、activeCount、createtaskCount

poolingCount:池中可用连接数

activeCount:正在使用的连接数

createTaskCount:正在生成的连接数

keepAlive:保活机制

maxActive:最大连接数

minIdle:最小连接数

notEmptyWaitThreadCount:用户正在等待连接的线程

CreateConnectionThread() 执行的initedLatch.countDown();这里是需要等待销毁线程创建完成后才会继续执行的。

private final CountDownLatch initedLatch = new CountDownLatch(2);
        public void run() {
            // 生产者线程这里需要等待销毁线程创建完成后才会继续执行,销毁线程初始化的时候也会执行initedLatch.countDown();
            initedLatch.countDown();

            long lastDiscardCount = 0;
            int errorCount = 0;
            for (; ; ) {
                // addLast
                try {
                    lock.lockInterruptibly();
                } catch (InterruptedException e2) {
                    break;
                }

                long discardCount = DruidDataSource.this.discardCount;
                boolean discardChanged = discardCount - lastDiscardCount > 0;
                lastDiscardCount = discardCount;

                try {
                    // 用来标记是否可以创建连接
                    boolean emptyWait = true;

                    if (createError != null
                            && poolingCount == 0
                            && !discardChanged) {
                        emptyWait = false;
                    }

                    if (emptyWait
                            && asyncInit && createCount < initialSize) {
                        emptyWait = false;
                    }

                    if (emptyWait) {
                        // 必须存在线程等待,才创建连接
                        /*
                            连接池中包含3部分:poolingCount、activeCount、createTaskCount(正在生成的连接数)
                            poolingCount:池中可用连接数
                            notEmptyWaitThreadCount: 等待的用户线程数量
                            keepAlive: 保活机制
                            poolingCount: 连接池中的空闲连接
                            activeCount: 正在使用的连接
                            minIdle
                            keepAlive && activeCount + poolingCount < minIdle 时会在shrink()触发emptySingal()来参加连接
                         */
                        if (poolingCount >= notEmptyWaitThreadCount //
                                && (!(keepAlive && activeCount + poolingCount < minIdle))
                                && !isFailContinuous()
                        ) {
                            // empty为Condition对象,empty.await()表示线程等待中,需要empty.signal()或者empty.signalAll()唤醒
                            empty.await();
                        }

                        // 防止创建超过maxActive数量的连接
                        /*

                            maxActive:连接池中的最大连接数
                            activeCount + poolingCount >= maxActive 时,创建连接的线程会被取消
                         */
                        if (activeCount + poolingCount >= maxActive) {
                            empty.await();
                            continue;
                        }
                    }

                } catch (InterruptedException e) {
                    lastCreateError = e;
                    lastErrorTimeMillis = System.currentTimeMillis();

                    if ((!closing) && (!closed)) {
                        LOG.error("create connection Thread Interrupted, url: " + jdbcUrl, e);
                    }
                    break;
                } finally {
                    lock.unlock();
                }

                // 创建物理连接
                PhysicalConnectionInfo connection = null;

                try {
                    connection = createPhysicalConnection();
                } catch (SQLException e) {
                    。。。
            }
        }

3、创建销毁线程DestroyConnectionThread

createAndStartDestroyThread()

    protected void createAndStartDestroyThread() {
        destroyTask = new DestroyTask();

        // 可以通过setDestroyScheduler()来自定义一个线程池,用来解决单线程销毁效率低的情况
        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线程执行的是destroyTask的run方法
        destroyConnectionThread = new DestroyConnectionThread(threadName);
        destroyConnectionThread.start();
    }

destroytask.run()中将要回收的连接放入abandonedList集合中

遍历这个集合中的pooledConnection连接,这些连接将被close掉

activeConnectionLock.lock();
        try {
            Iterator<DruidPooledConnection> iter = activeConnections.keySet().iterator();

            // 遍历正在使用的连接
            for (; iter.hasNext(); ) {
                DruidPooledConnection pooledConnection = iter.next();

                // 判断改连接是否还在运行,不运行则回收
                if (pooledConnection.isRunning()) {
                    continue;
                }

                long timeMillis = (currrentNanos - pooledConnection.getConnectedTimeNano()) / (1000 * 1000);

                // removeAbandonedTimeoutMillis: 连接回收的超时时间,默认300秒
                // 如果当前连接使用的时间 大于 超时时间阈值,则该连接将被回收
                if (timeMillis >= removeAbandonedTimeoutMillis) {
                    iter.remove();
                    pooledConnection.setTraceEnable(false);
                    abandonedList.add(pooledConnection);
                }
            }
        } finally {
            activeConnectionLock.unlock();
        }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zyc_2754

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值