Connection Leaks in JDBC — Prevention and Detection
Fast recall
Quick revision
Core answer
Whether you can define a connection leak and prevent it with try-with-resources.
Closing only on the happy path, or relying on GC to return connections.
Mention leakDetectionThreshold for diagnosing leaks in production.
Interview-ready guide
Interview answer
A missing close on an exception path may leave each failed request holding one connection. Once all pool connections are checked out, new requests queue and eventually receive a connection-acquisition timeout. Declare the Connection in try-with-resources and nest statements/results inside it. In Spring transaction-managed code, let the framework own the connection rather than closing a borrowed transactional resource manually.
For example, if an exception skips connection.close(), a ten-connection pool can eventually leave all ten connections active and new requests time out. try-with-resources and pool leak diagnostics make that path visible and safe.
Connection Leaks in JDBC — Prevention and Detection
Direct Answer
A JDBC connection leak occurs when application code borrows a connection and fails to close it, so a pool cannot reuse it. Repeated leaks exhaust the pool; later callers wait until connectionTimeout and then fail rather than necessarily hanging forever. Use try-with-resources, short ownership scopes, metrics, and Hikari leakDetectionThreshold as a diagnostic aid.
Common Mistakes & Pitfalls
Closing only on the happy path, or relying on GC to return connections.
Check your understanding
Answer these without looking back at the article.
- What is connection pooling and why is it critical for production Java applications?
- What is HikariCP and how do you configure it in Spring Boot?
- What happens when all connections in a pool are in use?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.