- 连接归还:com.zaxxer.hikari.pool.ProxyConnection#close,顺序关闭 Statement,提交或回滚事务,归还 Connection;
- 数据源关闭: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();
}
});
}
}
可以看出,关闭连接的主要内容有:
- 将 PoolEntry evict 状态设置为的 true;
- 让 PoolEntry 无法被 borrow 到(调用 reserve 方法);
- PoolEntry 的 Connection 设置为 null (poolEntry.close());
- 真正关闭连接;
可以注意到,poolEntry.close()
只是将 Connection 设置为 null,真正调用 JDBC 中 connection.close()
是通过 closeConnectionExecutor 线程池完成的。
有个需要注意之处就是,此时 closeConnectionExecutor 在关闭物理连接之后又对连接池状态进行了判断,如果状态为 POOL_NORMAL
则进行 fillPool()
. 这是因为 closeConnection 并不只是在关闭数据源的时候被调用,在连接池正常运行时也会被调用:
- getConnection() 时;
- 管家线程在运行时;