skip to content

A nightly jOOQ export of a few million rows exhausts the heap or leaks connections; which fetch method should it use, and what must it close?

level: seniorimportance: should knowfreq 45%

answer

  1. eager is the default
  2. for-each still calls fetch()
  3. Cursor or Stream, try-with-resources
  4. driver buffering and fetchSize
  5. autocommit on PostgreSQL

basics

~20 s

Use fetchLazy() for a Cursor, or fetchStream(), inside try-with-resources, and set fetchSize so the driver does not buffer everything. fetch() and for-each loops materialise every row; an unclosed Cursor or Stream holds its statement, result set and connection.

solid answer

~40 s

Most jOOQ fetch methods are eager: `fetch()` reads the whole `ResultSet` into a `Result`, and iterating a `ResultQuery` in a for-each loop calls `fetch()` too. For millions of rows use `fetchLazy()`, which returns a `Cursor` holding the open `PreparedStatement` and `ResultSet`, or `fetchStream()`, built on the same cursor. The cursor closes itself after the last record, but an early exit or exception leaves it open, so wrap either in try-with-resources. jOOQ reading lazily is not enough: many drivers buffer the full result unless you set `fetchSize(int)` or `Settings.withFetchSize`, and jOOQ's Javadoc warns that PostgreSQL does not like a fetch size combined with autocommit, so run the export in a transaction. Also check `Settings.fetchIntermediateResult`: if a team set it to `ALWAYS`, `fetchStream()` materialises a full `Result` first.

code

java · 8 lines
java
import static com.example.db.Tables.CUSTOMER;
import com.example.db.tables.records.CustomerRecord;

try (java.util.stream.Stream<CustomerRecord> rows = ctx.selectFrom(CUSTOMER)
        .fetchSize(1_000)
        .fetchStream()) {
    rows.map(CsvLine::from).forEach(writer::write);
}

go deeper

for a junior

Recall that fetch() loads every row into memory, and that fetchLazy() and fetchStream() exist for large results and must be closed.

for a middle

Explain that a for-each over a ResultQuery still calls fetch(), and that a Cursor closes itself only after the last record.

for a senior

Diagnose heap growth versus connection leaks separately: driver buffering, fetchSize and autocommit for the first, try-with-resources on failure paths for the second.

for a principal

Set a rule that large reads go through lazy fetches in try-with-resources with an explicit fetch size, and watch pool metrics for leaks.

## Why the export breaks Two different symptoms usually have two different causes. - **Heap exhaustion**: something held every row in memory at once, either jOOQ's eager `Result` or the JDBC driver's own buffer. - **Connection leaks**: a lazy fetch was opened and never closed, so its statement, result set and the connection behind them stay checked out. Whether to stream at all is a general data-access question; this answer is about which jOOQ calls do it and what each one obliges you to close. ## Eager versus lazy in jOOQ The `ResultQuery` Javadoc is explicit: most ways of fetching load the entire `ResultSet` eagerly, so that JDBC resources can be closed immediately and you need not manage them. | Call | Memory | You must close | |---|---|---| | `fetch()`, `fetchArray()`, `fetchMap(...)` | Every row in a `Result` or collection | Nothing | | `for (R r : query)` / `query.forEach(...)` | Every row: `iterator()` delegates to `fetch()` | Nothing | | `fetchLazy()` | One row at a time through a `Cursor` | The `Cursor` | | `fetchStream()` / `stream()` | One row at a time, backed by a lazy `Cursor` | The `Stream` | | `collect(Collector)` | Depends on the collector | Nothing: jOOQ manages the cursor | The for-each row catches people out: a `ResultQuery` is `Iterable`, which looks lazy, but its iterator runs `fetch()` first. ## Closing a Cursor or Stream A `Cursor` keeps a reference to the executed `PreparedStatement` and its `ResultSet`. Its Javadoc states two facts worth quoting at their exact strength: 1. Client code must close the cursor to close the underlying statement and result set. 2. If you fetch **all** records, the cursor closes itself. So the happy path cleans up, and the failure path does not. A `break` on a bad row, an exception from the writer, or a timeout leaves the cursor open, and the connection it uses cannot return to the pool. The fix is try-with-resources, which both `Cursor` (`AutoCloseable`) and `Stream` support: ```java import org.jooq.Cursor; import static com.example.db.Tables.CUSTOMER; import com.example.db.tables.records.CustomerRecord; try (Cursor<CustomerRecord> cursor = ctx.selectFrom(CUSTOMER) .fetchSize(1_000) .fetchLazy()) { for (CustomerRecord r : cursor) { writer.write(r); } } ``` A `Cursor` offers a single iterator only, plus `fetchNext()` and `fetchNext(int)` for record-by-record or batch-by-batch reads. A `Stream` from `fetchStream()` closes its cursor in `onClose`, which runs only when the stream itself is closed. ## The driver can still buffer everything jOOQ reading lazily does not stop the JDBC driver from reading eagerly. The `fetchSize(int)` Javadoc notes that, depending on the driver, the whole result may still land in the driver's memory, and gives two dialect remarks: - **PostgreSQL**: the Javadoc says it does not like fetch sizes combined with `autoCommit == true`, because its driver only reads in batches with autocommit off. Run the export inside a transaction. - **MySQL** uses `Integer.MIN_VALUE` as the fetch size to stream row by row, together with a forward-only, read-only result set. `Settings.withFetchSize(Integer)` sets a default for a whole configuration (the default is `0`, meaning the driver's own default), and a per-query `fetchSize(int)` overrides it. ## A setting that silently re-materialises `Settings.fetchIntermediateResult` defaults to `WHEN_RESULT_REQUESTED`. If someone set it to `ALWAYS`, or to `WHEN_EXECUTE_LISTENERS_PRESENT` with listeners registered, `fetchStream()` and `collect()` first build a full `Result` so listeners can see it. A streaming export then behaves like `fetch()`. Check this before blaming the driver. ## Cursor, Stream or collect - **`Cursor`** suits imperative loops and chunked work: `fetchNext(int)` returns the next block of records as a small `Result`, handy for writing in batches. - **`Stream`** suits a pipeline of `map` and `filter` steps, as long as the whole pipeline sits inside try-with-resources. - **`collect(Collector)`** suits a single reduction, such as summing or grouping into a small map, because jOOQ opens and closes the cursor inside the call. ## Diagnosis order 1. Find the fetch call: `fetch()`, a for-each over the query, or a lazy call? 2. If lazy, is it inside try-with-resources on every path? 3. Is a fetch size set, and on PostgreSQL is autocommit off for this work? 4. Is `fetchIntermediateResult` at its default? 5. Watch pool metrics: a slow leak of checked-out connections after failed runs points to an unclosed cursor.

  • In jOOQ, why does ResultQuery.collect(Collector) not need try-with-resources while fetchStream() does?
    `collect()` opens the cursor internally and closes it when collection ends, so no resource escapes the call. `fetchStream()` returns an open `Stream` to you, and its cursor closes only when that stream is closed. Use `collect()` when a collector can express the whole job.
  • A jOOQ export with a Cursor runs fine for weeks, then the pool empties after a run of failed nights. What is the likely cause?
    The happy path consumed every row, so the cursor closed itself. On failing nights the loop exited early, and without try-with-resources the cursor, its statement and its connection stayed open. Each failure leaked one connection until the pool ran dry.

A jOOQ Cursor is a reading-room seat in a library: you read the book page by page instead of photocopying it all, but the seat stays yours until you hand it back, even if you walk out halfway.

  • Iterating a ResultQuery in a for-each loop streams rows lazily
  • A jOOQ Cursor always closes itself when the loop exits
  • fetchLazy() alone guarantees the driver does not buffer the result
  • fetchSize works on PostgreSQL regardless of autocommit
  • fetchStream() never builds a full Result in memory

Assumes jOOQ 3.21, where fetchStream() is backed by a lazy Cursor unless Settings.fetchIntermediateResult asks for a full Result first.