How does try-with-resources prevent JDBC connection and file-handle leaks?
⚡ Short Answer
try-with-resources auto-closes any AutoCloseable in reverse order, even on exception, and suppresses-but-preserves close() errors. It replaces error-prone finally blocks that leak connections when close() itself throws or is forgotten.
☕Coffee Chat Question
Concept Made Simple
“How does try-with-resources prevent JDBC connection and file-handle leaks?”
🧠Mind Map Answer
Remember It Faster
Resources declared in try (...) get close() called automatically — no manual finally, no leak if the body throws. Closes happen in reverse declaration order.
⌨️Hands-on Keyboard
Learn by Doing
try (Connection c = ds.getConnection();
PreparedStatement ps = c.prepareStatement(SQL)) {
ps.setLong(1, id);
return ps.executeQuery();
} // c & ps closed automatically, even on exception🔥What If?
Think Beyond the Expected
Your pool reports 'connection leak detected' under load — likely cause?
A code path acquires a Connection but an exception skips a manual close (or close() is in the wrong place). Switching to try-with-resources guarantees release on every path; pool 'leak detection' just surfaces the unreturned connection.
😂Real World
Connection-pool exhaustion (HikariCP timeouts) under peak load almost always traces to a non-try-with-resources path leaking connections during exceptions.
🎯Interviewer's Expectation
Keywords they're listening for:
⚠️Common Mistakes
- ✗Closing in catch instead of finally/try-with-resources
- ✗Ignoring exceptions thrown by close()
- ✗Reusing a resource after the try block
✅Best Practices
- ✓Always acquire closeable resources in try-with-resources
- ✓Keep one resource per declaration for clarity
- ✓Set a pool leakDetectionThreshold in non-prod to catch leaks early
🔁Follow-up Questions
- 1What is a suppressed exception and how do you read it?
- 2Why does HikariCP report leaks via leakDetectionThreshold?
- 3Order of close when multiple resources throw?
🧩Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly — AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: Exceptions (Core Java) Interview question: "How does try-with-resources prevent JDBC connection and file-handle leaks?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
⭐ Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission — at no extra cost to you. It helps keep Full Stack Interview Guru free.