HikariCP 连接归还与数据源关闭

  1. 连接归还:com.zaxxer.hikari.pool.ProxyConnection#close,顺序关闭 Statement,提交或回滚事务,归还 Connection;
  2. 数据源关闭:com.zaxxer.hikari.HikariDataSource#close,真正的移除数据库连接,关闭数据源;

连接归还

连接归还发生在

归还的时序图:
归还连接
HikariCP 在归还连接时会自动关闭 Statement,代码如下:

   private synchronized void closeStatements()
   {
      final int size = openStatements.size();
      if (size > 0) {
         for (int i = 0; i < size && delegate != ClosedConnection.CLOSED_CONNECTION; i++) {
            try (Statement ignored = openStatements.get(i)) {
               // automatic resource cleanup
            }
            catch (SQLException e) {
               LOGGER.warn("{} - Connection {} marked as broken because of an exception closing open statements during Connection.close()",
                           poolEntry.getPoolName(), delegate);
               leakTask.cancel();
               poolEntry.evict("(exception closing Statements during Connection.close())");
               delegate = ClosedConnection.CLOSED_CONNECTION;
            }
         }

         openStatements.clear();
      }
   }
   
   @Override
   public final void close() throws SQLException
   {
      // Closing statements can cause connection eviction, so this must run before the conditional below
      closeStatements();

      if (delegate != ClosedConnection.CLOSED_CONNECTION) {
         leakTask.cancel();

         try {
            if (isCommitStateDirty && !isAutoCommit) {
               delegate.rollback();
               lastAccess = currentTime();
               LOGGER.debug("{} - Executed rollback on connection {} due to dirty commit state on close().", poolEntry.getPoolName(), delegate);
            }

            if (dirtyBits != 0) {
               poolEntry.resetConnectionState(this, dirtyBits);
               lastAccess = currentTime();
            }

            delegate.clearWarnings();
         }
         catch (SQLException e) {
            // when connections are aborted, exceptions are often thrown that should not reach the application
            if (!poolEntry.isMarkedEvicted()) {
               throw checkException(e);
            }
         }
         finally {
            delegate = ClosedConnection.CLOSED_CONNECTION;
            poolEntry.recycle(lastAccess);
         }
      }
   }

可以看出,在 close() 中以 try-with-resource 的方式关闭了 Statement . 连接归还实际上就是调用 ConcurrentBag#requite 方法将 PoolEntry 状态设置为 STATE_NOT_IN_USE,代码如下:

   public void requite(final T bagEntry)
   {
      bagEntry.setState(STATE_NOT_IN_USE);

      for (int i = 0; waiters.get() > 0; i++) {
         if (bagEntry.getState() != STATE_NOT_IN_USE || handoffQueue.offer(bagEntry)) {
            return;
         }
         else if ((i & 0xff) == 0xff) {
            parkNanos(MICROSECONDS.toNanos(10));
         }
         else {
            Thread.yield();
         }
      }

      final List<Object> threadLocalList = threadList.get();
      if (threadLocalList.size() < 50) {
         threadLocalList.add(weakThreadLocals ? new WeakReference<>(bagEntry) : bagEntry);
      }
   }

关闭连接

关闭连接的时序图:
关闭连接
关闭连接的主要逻辑为软驱逐连接,调用 Connection 的 close 方法真正关闭连,代码如下:

   private boolean softEvictConnection(final PoolEntry poolEntry, final String reason, final boolean owner)
   {
      poolEntry.markEvicted();
      if (owner || connectionBag.reserve(poolEntry)) {
         closeConnection(poolEntry, reason);
         return true;
      }

      return false;
   }
   
   void closeConnection(final PoolEntry poolEntry, final String closureReason)
   {
      if (connectionBag.remove(poolEntry)) {
         final Connection connection = poolEntry.close();
         closeConnectionExecutor.execute(() -> {
            quietlyCloseConnection(connection, closureReason);
            if (poolState == POOL_NORMAL) {
               fillPool();
            }
         });
      }
   }

可以看出,关闭连接的主要内容有:

  1. 将 PoolEntry evict 状态设置为的 true;
  2. 让 PoolEntry 无法被 borrow 到(调用 reserve 方法);
  3. PoolEntry 的 Connection 设置为 null (poolEntry.close());
  4. 真正关闭连接;

可以注意到,poolEntry.close() 只是将 Connection 设置为 null,真正调用 JDBC 中 connection.close() 是通过 closeConnectionExecutor 线程池完成的。

有个需要注意之处就是,此时 closeConnectionExecutor 在关闭物理连接之后又对连接池状态进行了判断,如果状态为 POOL_NORMAL 则进行 fillPool() . 这是因为 closeConnection 并不只是在关闭数据源的时候被调用,在连接池正常运行时也会被调用:

  1. getConnection() 时;
  2. 管家线程在运行时;
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值