getConnection()未赋值变量会泄漏连接吗?JDBC连接池代码疑问
Do These Two Scenarios Cause JDBC Connection Leaks?
Great question—let's break down both cases clearly to understand if they lead to connection leaks, and why:
Scenario 1: Calling getConnection() without assigning to a variable
- When you call
getConnection(), the connection pool pulls an active connection from its pool and hands it to your application. - Since you don’t store a reference to this connection object, you have no way to call
close()on it. - This leaves the connection marked as "in use" by the pool indefinitely (unless the pool has an idle timeout configured, which is a safety net, not a proper fix).
- This absolutely causes a connection leak. Over time, your pool will exhaust all available connections because they’re all stuck in the "in use" state, leading to
NoSuchConnectionerrors or application hangs.
Scenario 2: Retrieving DatabaseMetaData without closing the underlying connection
- Let’s look at your code snippet:
DatabaseMetaData dbMeta = getConnection().getMetaData(); - Here,
getConnection()grabs a connection from the pool, which is then used to create theDatabaseMetaDatainstance. But since you don’t keep a reference to the original connection, you can’t callclose()on it. - Even though
DatabaseMetaDatais tied to the connection it came from, garbage collection won’t automatically close the connection. Connection pools don’t rely on GC to reclaim connections—they require an explicitclose()call to mark the connection as available for reuse. - Without that
close()call, the connection stays in the "in use" state, just like in scenario 1. - This also causes a connection leak. The pool can’t reuse that connection until you explicitly return it, so you’re wasting a valuable pool resource.
Quick Fix: Use Try-With-Resources
To avoid these leaks entirely, always use Java’s try-with-resources statement (introduced in Java 7). It automatically closes the connection when you’re done with it, even if an exception occurs:
try (Connection conn = getConnection()) { DatabaseMetaData dbMeta = conn.getMetaData(); // Do your work with dbMeta here } // conn is automatically closed and returned to the pool here
内容的提问来源于stack exchange,提问作者Prasanna
相关产品推荐
相关产品推荐

