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

1、init过程中创建的三个线程

在init过程中,会创建物理连接
接下来创建三个线程

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

2、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
            }
        }
    }

3、创建守护线程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) {
                    。。。
            }
        }

4、创建销毁线程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();
        }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容