ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 6 · Databases, APIs & Integration
  4. Volume III
  5. Resource Management
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
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
Covers
Connection; Statement; ResultSet closing
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally — try-with-resources
  5. 4A. Deep Dive — Leaks: Symptoms, Detection and Prevention
  6. 5. APIs / Features / Syntax
  7. 6. Practical Examples
  8. 7. Common Problems & Mistakes
  9. 8. Performance & Production Considerations
  10. 9. Architecture & Design Considerations
  11. 10. Interview Questions & Answers

1Concept / Definition

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.

Resources are nested — close inner before outer
Figure 1 — Resources are nested — close inner before outer
ResourceHoldsClosing does
ConnectionSocket, backend process, transaction, pool slotReturns to pool (pooled) or disconnects (unpooled)
StatementServer prepared statement, buffersReleases client/server statement resources (or returns to statement cache)
ResultSetCursor/portal, buffered rowsReleases 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

RuleReason
Borrow late, return earlyPool slots and transactions are shared capacity
One owner closes itThe code (or framework) that obtained it
Don't store connections in fieldsLong-held connections become leaks
Don't pass connections across threadsJDBC connections aren't designed for concurrent use
End the transaction before closingPool rolls back leftovers, but explicit is clearer
Table 2 — Connection ownership rules

3.2 Statement

RuleReason
Close each statement after useFrees server-side statement and memory
Closing a statement closes its ResultSetSpec behaviour — but close ResultSets explicitly anyway
Reusing a PreparedStatement in a loop is fineClose once after the loop
Statement caching is the driver's jobPgJDBC caches by SQL text per connection
Table 3 — Statement rules

3.3 ResultSet closing

RuleReason
Close as soon as rows are consumedCursor/portal and buffered rows held otherwise
Don't return a ResultSet from a methodCaller can't know when the connection may be released
Map to objects/records inside the scopeHand out data, not cursors
Streams over ResultSets must be closedStream wraps a live cursor and connection
Table 4 — ResultSet rules
finally blocks vs try-with-resources
Figure 2 — finally blocks vs try-with-resources
JAVA
// Correct: all three resources in try-with-resources headers
public 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 behaviourEffect
Resources closed in reverse declaration orderResultSet → Statement → Connection
close() called even when the body throwsNo leak on exception
Exception from close() while another is propagatingAdded via addSuppressed() — original kept
Null resources skippedSafe with factories that may return null
Java 9+: effectively final variables allowedtry (con; ps) { … }
Table 5 — Semantics of try-with-resources
What close() does at each level
Figure 3 — What close() does at each level

4ADeep Dive — Leaks: Symptoms, Detection and Prevention

A leak accumulates until the pool is empty
Figure 4 — A leak accumulates until the pool is empty
Leak typeSymptomDetection
Connection not closedPool active count ratchets up; eventually timeoutsHikariCP leakDetectionThreshold stack trace
Connection held too long (not a leak, same effect)High usage time, pending threadshikaricp_connections_usage_seconds
Open transaction on returned connectionidle in transaction sessions (if pool doesn't reset)pg_stat_activity
Unclosed ResultSet in a long transactionMemory growth, open portalsHeap dumps; server pg_cursors
Unclosed Stream<T> from repositoryConnection held until stream closedLeak 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 follows
java.lang.Exception: Apparent connection leak detected
    at com.shop.export.OrderExporter.export(OrderExporter.java:42)

5APIs / Features / Syntax

APIPurpose
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 / JdbcClientFramework-managed resources
DataSourceUtils.getConnection/releaseConnectionTransaction-aware manual access in Spring
HikariCP leakDetectionThresholdLeak 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

JAVA
// Pre-Java 7 style — correct, but look at it
Connection con = null; PreparedStatement ps = null; ResultSet rs = null;
try {
    con = dataSource.getConnection();
    ps = con.prepareStatement(SQL);
    rs = ps.executeQuery();
    return map(rs);
} finally {
    if (rs != null) try { rs.close(); } catch (SQLException ignore) { }
    if (ps != null) try { ps.close(); } catch (SQLException ignore) { }
    if (con != null) try { con.close(); } catch (SQLException ignore) { }
}
Weakness of manual finallytry-with-resources
Close errors swallowed or maskingSuppressed, original kept
Easy to forget a resourceCompiler-enforced scope
Verbose → copy-paste bugsConcise
Table 8 — Why the modern form is mandatory

6.4 Worked example — returning data, not cursors

JAVA
// WRONG: caller receives a live ResultSet; connection can't be released safely
public ResultSet findOrders(long customerId) { … }
 
// RIGHT: map inside the scope, return values
public 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
public interface 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/connection
public void 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 patterntry-with-resources
B from close() replaces A → root cause lostA propagates; B attached as suppressed
Table 9 — Root cause preserved

6.7 Worked example — resources and virtual threads

ConcernGuidance
Thousands of virtual threads each calling getConnection()Pool still limits concurrency (good) — keep connectionTimeout short
Holding a connection while blocking on I/OSame leak-like effect as with platform threads
synchronized blocks in older drivers pinning carrier threadsUse current PgJDBC/HikariCP versions (JDK 24+ removed most pinning for synchronized)
ThreadLocal-bound transactionsWork 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 all
long count = jdbcClient.sql("SELECT count(*) FROM purchase_order WHERE status = :s")
                       .param("s", "PAID")
                       .query(Long.class)
                       .single();
LayerWho closes resources
Plain JDBCYou (try-with-resources)
JdbcTemplate / JdbcClientSpring, in all paths
JPA / HibernateProvider (connection released after transaction or statement)
Spring Data streamsYou close the Stream; Spring closes the rest
Table 11 — Know which layer owns cleanup

6.9 Worked example — finding the leaking code path

StepAction
1Observe hikaricp_connections_active rising without returning to baseline
2Enable leak-detection-threshold: 20000 (safe in production)
3Collect the logged stack traces; group by top application frame
4Reproduce error paths in tests; assert active connections return to 0
5Fix with try-with-resources / framework APIs; keep leak detection on
Table 12 — Leak investigation runbook
JAVA
@AfterEach
void noLeakedConnections(@Autowired HikariDataSource ds) {
    assertThat(ds.getHikariPoolMXBean().getActiveConnections()).isZero();
}

6.10 Worked example — lint rules for resource safety

ToolRule
SpotBugsOBL_UNSATISFIED_OBLIGATION, ODR_OPEN_DATABASE_RESOURCE
SonarQube"Resources should be closed" (java:S2095)
Error ProneMustBeClosedChecker with @MustBeClosed annotations
IntelliJ inspections"AutoCloseable used without try-with-resources"
Table 13 — Catch leaks at build time
Resource ownership rules
Figure 5 — Resource ownership rules

6.11 Worked example — resource scope in a layered service

LayerHolds a connection?Rule
ControllerNoNever touches JDBC; receives DTOs
Service (@Transactional)Yes, for the transaction's durationKeep short; no remote calls inside
Repository / DAOUses the service's connectionOpens/closes statements and result sets only
View rendering / JSON serialisationNo (open-in-view=false)Data fully loaded before leaving the service
Table 14 — Connection lifetime follows transaction boundaries
YAML
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

EndpointMean hold time (usage)QueriesFinding
GET /orders6 ms3Healthy
GET /orders/export41 s1 (streamed)Expected — dedicated pool for exports
POST /checkout820 ms9Payment call inside transaction → refactor
GET /dashboard2.3 s48N+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

AspectGuideline
Leak detectionOn in production at a threshold above normal transaction time
Pool metricsAlert when active count doesn't return to baseline
Server sideWatch idle in transaction, open cursors
TestsAssert zero active connections after each integration test
Static analysisResource 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.

Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.