Book 6 · Volume III — Java Persistence & Data Access Architecture · Topic 1.4
Resource Management
Closing connections, statements and result sets
9 min readStage 3 · Systems8 interview questions
Written byMaheshFounder · Senior Technical Architect
Chapter
Chapter 1 — JDBC
Prerequisites
Topics 1.1–1.3
You will be able to
Explain which client and server resources each JDBC object holds, close them correctly in every code path with try-with-resources, recognise leaks and their symptoms, handle streams and cursors safely, and rely on framework-managed resource handling where appropriate
Resource management in JDBC means acquiring connections, statements and result sets only as long as needed and always closing them — on success and on every exception path.
Figure 1 — Resources are nested — close inner before outer
Resource
Holds
Closing does
Connection
Socket, backend process, transaction, pool slot
Returns to pool (pooled) or disconnects (unpooled)
Statement
Server prepared statement, buffers
Releases client/server statement resources (or returns to statement cache)
ResultSet
Cursor/portal, buffered rows
Releases cursor and memory
Table 1 — What each resource holds
2Why It Exists
Database resources are scarce and shared: a pool has a handful of connections, the server has limited backends and memory for cursors. Garbage collection does not help — finalisation is unpredictable (and deprecated for removal), and an unreturned pooled connection is still referenced by the pool. Before Java 7, correct cleanup required deeply nested finally blocks; try-with-resources made correct code the concise code.
3Core Concepts
3.1 Connection
Rule
Reason
Borrow late, return early
Pool slots and transactions are shared capacity
One owner closes it
The code (or framework) that obtained it
Don't store connections in fields
Long-held connections become leaks
Don't pass connections across threads
JDBC connections aren't designed for concurrent use
End the transaction before closing
Pool rolls back leftovers, but explicit is clearer
Table 2 — Connection ownership rules
3.2 Statement
Rule
Reason
Close each statement after use
Frees server-side statement and memory
Closing a statement closes its ResultSet
Spec behaviour — but close ResultSets explicitly anyway
Reusing a PreparedStatement in a loop is fine
Close once after the loop
Statement caching is the driver's job
PgJDBC caches by SQL text per connection
Table 3 — Statement rules
3.3 ResultSet closing
Rule
Reason
Close as soon as rows are consumed
Cursor/portal and buffered rows held otherwise
Don't return a ResultSet from a method
Caller can't know when the connection may be released
Map to objects/records inside the scope
Hand out data, not cursors
Streams over ResultSets must be closed
Stream wraps a live cursor and connection
Table 4 — ResultSet rules
Figure 2 — finally blocks vs try-with-resources
JAVA
// Correct: all three resources in try-with-resources headerspublic Optional<Customer> findByEmail(String email) throws SQLException { String sql = "SELECT customer_id, full_name, email FROM customer WHERE email = ?";try (Connection con = dataSource.getConnection(); PreparedStatement ps = con.prepareStatement(sql)) { ps.setString(1, email);try (ResultSet rs = ps.executeQuery()) {return rs.next() ? Optional.of(new Customer(rs.getLong(1), rs.getString(2), rs.getString(3))) : Optional.empty(); } } // closes rs, ps, con in reverse order — even if an exception is thrown}
4How It Works Internally — try-with-resources
Compiler-generated behaviour
Effect
Resources closed in reverse declaration order
ResultSet → Statement → Connection
close() called even when the body throws
No leak on exception
Exception from close() while another is propagating
Added via addSuppressed() — original kept
Null resources skipped
Safe with factories that may return null
Java 9+: effectively final variables allowed
try (con; ps) { … }
Table 5 — Semantics of try-with-resources
Figure 3 — What close() does at each level
4ADeep Dive — Leaks: Symptoms, Detection and Prevention
Figure 4 — A leak accumulates until the pool is empty
Leak type
Symptom
Detection
Connection not closed
Pool active count ratchets up; eventually timeouts
HikariCP leakDetectionThreshold stack trace
Connection held too long (not a leak, same effect)
High usage time, pending threads
hikaricp_connections_usage_seconds
Open transaction on returned connection
idle in transaction sessions (if pool doesn't reset)
pg_stat_activity
Unclosed ResultSet in a long transaction
Memory growth, open portals
Heap dumps; server pg_cursors
Unclosed Stream<T> from repository
Connection held until stream closed
Leak detection; code review
Table 6 — Leak catalogue
YAML
spring: datasource: hikari: leak-detection-threshold: 20000 # log borrower stack trace if held > 20 s
TEXT
WARN com.zaxxer.hikari.pool.ProxyLeakTask - Connection leak detection triggered for org.postgresql.jdbc.PgConnection@4f2b… on thread http-nio-8080-exec-7, stack trace followsjava.lang.Exception: Apparent connection leak detected at com.shop.export.OrderExporter.export(OrderExporter.java:42)
5APIs / Features / Syntax
API
Purpose
try (A a = …; B b = …) { … }
Automatic closing
Throwable.getSuppressed()
Inspect close-time failures
Statement.closeOnCompletion()
Close statement when its ResultSet closes
ResultSet.isClosed(), Connection.isClosed()
Defensive checks (rarely needed)
Spring JdbcTemplate / JdbcClient
Framework-managed resources
DataSourceUtils.getConnection/releaseConnection
Transaction-aware manual access in Spring
HikariCP leakDetectionThreshold
Leak diagnostics
Table 7 — Resource management API
6Practical Examples
6.1 The error-path leak
A DAO closed its connection at the end of the happy path only. When a validation exception occurred between getConnection() and close(), the connection leaked. Twenty failed requests later, the pool (size 20) was empty and the service returned 500s until restart. try-with-resources fixed it in five lines.
6.2 The un-closed stream
A Spring Data method returned Stream<Order>; the controller consumed it lazily without closing. Each call leaked a connection until GC — which never came because the pool referenced it. Wrapping in try-with-resources inside a @Transactional(readOnly = true) service method fixed it.
6.3 Worked example — manual cleanup vs try-with-resources
// WRONG: caller receives a live ResultSet; connection can't be released safelypublic ResultSet findOrders(long customerId) { … }// RIGHT: map inside the scope, return valuespublic List<OrderRow> findOrders(long customerId) {return jdbcClient.sql(""" SELECT order_id, total FROM purchase_order WHERE customer_id = :c""") .param("c", customerId) .query(OrderRow.class) .list();}
6.5 Worked example — streaming safely with Spring Data
JAVA
publicinterface OrderRepository extends JpaRepository<Order, Long> {@QueryHints(@QueryHint(name = HibernateHints.HINT_FETCH_SIZE, value = "500")) Stream<Order> streamByStatus(OrderStatus status);}@Transactional(readOnly = true) // stream needs an open transaction/connectionpublicvoid exportPaid(Consumer<Order> sink) {try (Stream<Order> orders = repository.streamByStatus(OrderStatus.PAID)) { orders.forEach(o -> { sink.accept(o); entityManager.detach(o); // keep the persistence context small }); } // cursor closed; connection returned at txn end}
6.6 Worked example — suppressed exceptions in practice
JAVA
try (Connection con = dataSource.getConnection(); PreparedStatement ps = con.prepareStatement(SQL)) { ps.executeUpdate(); // throws SQLException A (constraint)} // con.close() throws B (network)catch (SQLException e) { log.error("Update failed", e); // e is A; B available via e.getSuppressed()}
Old finally pattern
try-with-resources
B from close() replaces A → root cause lost
A propagates; B attached as suppressed
Table 9 — Root cause preserved
6.7 Worked example — resources and virtual threads
Concern
Guidance
Thousands of virtual threads each calling getConnection()
Pool still limits concurrency (good) — keep connectionTimeout short
Holding a connection while blocking on I/O
Same leak-like effect as with platform threads
synchronized blocks in older drivers pinning carrier threads
Use current PgJDBC/HikariCP versions (JDK 24+ removed most pinning for synchronized)
ThreadLocal-bound transactions
Work with virtual threads; don't share connections across threads
Table 10 — Virtual threads change scale, not the rules
6.8 Worked example — framework-managed resources
JAVA
// JdbcClient: no Connection/Statement/ResultSet in user code at alllong count = jdbcClient.sql("SELECT count(*) FROM purchase_order WHERE status = :s") .param("s", "PAID") .query(Long.class) .single();
Layer
Who closes resources
Plain JDBC
You (try-with-resources)
JdbcTemplate / JdbcClient
Spring, in all paths
JPA / Hibernate
Provider (connection released after transaction or statement)
Spring Data streams
You close the Stream; Spring closes the rest
Table 11 — Know which layer owns cleanup
6.9 Worked example — finding the leaking code path
Step
Action
1
Observe hikaricp_connections_active rising without returning to baseline
2
Enable leak-detection-threshold: 20000 (safe in production)
3
Collect the logged stack traces; group by top application frame
4
Reproduce error paths in tests; assert active connections return to 0
5
Fix with try-with-resources / framework APIs; keep leak detection on
spring: jpa: open-in-view: false # connection released when the service transaction ends
With open-in-view enabled (Spring Boot's default, with a warning), the connection can stay bound until the HTTP response is written — rendering time becomes connection-holding time.
6.12 Worked example — measuring hold time per endpoint
Endpoint
Mean hold time (usage)
Queries
Finding
GET /orders
6 ms
3
Healthy
GET /orders/export
41 s
1 (streamed)
Expected — dedicated pool for exports
POST /checkout
820 ms
9
Payment call inside transaction → refactor
GET /dashboard
2.3 s
48
N+1 + open-in-view → fix fetch plan, disable OSIV
Table 15 — Hold time reveals resource-management problems before leaks do
Micrometer's hikaricp_connections_usage_seconds combined with trace spans per endpoint gives this table.
7Common Problems & Mistakes
Closing only on the happy path.
Returning ResultSets or open Streams from data-access methods.
Storing connections in fields or static variables.
Swallowing close() exceptions that hide root causes (manual finally).
Forgetting that Stream<T> repository methods hold connections.
Disabling leak detection instead of fixing leaks.
8Performance & Production Considerations
Aspect
Guideline
Leak detection
On in production at a threshold above normal transaction time
Pool metrics
Alert when active count doesn't return to baseline
Server side
Watch idle in transaction, open cursors
Tests
Assert zero active connections after each integration test
Static analysis
Resource rules as build-breaking
Table 16 — Operational guidelines
9Architecture & Design Considerations
Prefer framework-managed access (JdbcClient, JPA, MyBatis) for application code.
Allow raw JDBC only in infrastructure modules with review and tests.
Design APIs to return values, not cursors; streaming only within transactional scopes.
Make leak detection and pool metrics part of platform observability.
10Interview Questions & Answers
Q1L1 · BasicConcept
Why must JDBC resources be closed?
JDBC objects hold resources that are scarce and that garbage collection will not free in time. A Connection holds a socket, a server backend process, possibly an open transaction and, when pooled, one of only a handful of pool slots. A Statement can hold a server-side prepared statement and buffers, and a ResultSet holds a cursor or portal and buffered rows. If you forget to close a pooled connection, the pool still tracks it as in use, so its slot is gone for good. Once all slots leak, every request waits for the connection timeout and fails, so one leaking error path can take down unrelated features of a service.
Q2L1 · BasicConcept
What is try-with-resources?
Try-with-resources is the Java 7 statement that declares one or more AutoCloseable resources in its header and guarantees that close() is called on each when the block exits, whether it completes normally, returns early or throws. Resources are closed in reverse order of declaration, so a ResultSet closes before its Statement and the Statement before its Connection. If the body throws and close() also throws, the close exception is attached to the original as a suppressed exception rather than replacing it. Since Java 9 you can also list effectively final variables declared earlier. It replaced nested finally blocks that were easy to get wrong, so correct cleanup became the short version.
Q3L2 · IntermediateInternals
In which order should JDBC resources be closed?
Close them in reverse order of creation: ResultSet, then Statement, then Connection. Each inner object depends on the outer one; a ResultSet reads through its Statement, which runs on its Connection, so closing the connection first leaves the others pointing at nothing. The JDBC specification says closing a Statement closes its current ResultSet, and closing a Connection releases its statements, but relying on that cascade is fragile across drivers and pools, where close() on a connection does not physically disconnect. Try-with-resources produces the right order automatically: declare the Connection first, then the PreparedStatement, and open the ResultSet in a nested try after setting parameters.
Q4L2 · IntermediateInternals
What does close() on a pooled connection do?
With a pool, getConnection() returns a proxy around a physical connection, and close() on that proxy does not disconnect anything. HikariCP rolls back uncommitted work, resets state the borrower changed, such as auto-commit, isolation level, read-only flag, catalog and schema, closes statements the borrower left open, and puts the connection back in the pool for the next caller. The socket and the server backend stay alive, which is the whole point of pooling. That is also why a missing close() is so damaging: the connection is never returned, so the usable pool shrinks permanently. Calling close() remains mandatory; with a pool it simply means return, not disconnect.
Q5L3 · Senior EngineerTricky
What happens to exceptions thrown by close() in try-with-resources?
If the try block throws an exception and close() then throws as well, try-with-resources keeps the original exception as the one that propagates and attaches the close() failure to it with addSuppressed(). You can read it through getSuppressed(), and stack traces print it under a Suppressed heading. If only close() throws, that exception propagates normally. This is a real improvement over the old finally pattern, where an exception from close() replaced the original, so a constraint violation could be reported as a network error and the root cause was lost. When logging, pass the exception object to the logger rather than just its message, so the suppressed exceptions are included.
Q6L3 · Senior EngineerTricky
Why is returning a Stream from a repository risky?
A Stream returned from a Spring Data repository is backed by a live database cursor, so it holds an open ResultSet and a connection until someone closes the stream. Spring Data requires the call to run inside a transaction, typically @Transactional(readOnly = true), and the caller must consume it in a try-with-resources block. If a controller returns it, or consumes it lazily without closing it, the connection stays checked out, and because the pool still tracks it, garbage collection never rescues it. The safe pattern is to stream inside a transactional service method, process each element, detach entities to keep the persistence context small, and return results, never the Stream itself.
Q7L4 · Technical ArchitectScenario
How do you detect connection leaks in production?
First, watch the pool metrics: hikaricp_connections_active climbing without returning to baseline, rising pending threads and connection-timeout errors are the classic signature. Second, enable HikariCP's leakDetectionThreshold, for example 20 seconds, which is safe in production and logs the stack trace of the code that borrowed a connection and held it too long. Group those traces by the top application frame to find the leaking path. On the database side, pg_stat_activity shows sessions idle in transaction and their last query. Tell true leaks apart from long holds by looking at hikaricp_connections_usage_seconds per endpoint. Then reproduce the error path in a test that asserts active connections return to zero.
Q8L5 · Solution ArchitectDesign
How do you prevent resource leaks across many teams?
Make leaks structurally unlikely, then make the rare one visible quickly. The default for application code is framework-managed access through JdbcClient, JdbcTemplate, JPA or MyBatis, so teams never touch Connection or ResultSet directly. Raw JDBC is allowed only in reviewed infrastructure modules and must use try-with-resources. Static analysis enforces this in CI, with SonarQube rule S2095, SpotBugs database resource checks or Error Prone's MustBeClosed checker. Integration tests assert zero active connections after each test. In production every service ships with leak detection enabled, pool metrics on the platform dashboard and alerts on pool wait time. Bake all of it into the shared service template so new services inherit it.