Quick revision
The short answer
All three can be lazy and keep memory flat if they are backed by a database cursor or by pages, but Iterator and Iterable have no close method, so a caller that stops early leaks the connection or cursor. A Stream implements AutoCloseable: with onClose registered and the caller using try-with-resources, cleanup is explicit and happens even on early exit. Spring Data supports Stream return types, which must be consumed inside a transaction, and the method should be documented as single-use.
What to remember
In this answer, we saw that a lazy result backed by a cursor or keyset pages keeps memory flat whichever type we return, but Iterator and Iterable have no close method, so callers who stop early leak cursors and connections, and Iterable even invites re-running the query. A Stream with onClose, used in try-with-resources, makes cleanup explicit. Spring Data streams must be consumed inside a transaction, the JPA persistence context must be kept small, a hand-written hasNext must be idempotent, and the result must be documented as single-use.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
All three can be lazy and keep memory flat if they are backed by a database cursor or by pages, but Iterator and Iterable have no close method, so a caller that stops early leaks the connection or cursor. A Stream implements AutoCloseable: with onClose registered and the caller using try-with-resources, cleanup is explicit and happens even on early exit. Spring Data supports Stream return types, which must be consumed inside a transaction, and the method should be documented as single-use.
Why this question is asked
Exporting a large table is a common task that quietly breaks systems. A naive findAll() on 50 million rows tries to build a list of 50 million objects and runs out of heap, and a careless lazy version leaks database connections until the pool is empty. Interviewers ask this design question to see whether we think about memory and resource ownership together, and whether we know what the JDK types promise. In this answer, we will see how to keep memory flat, compare the three return types on the question of cleanup, write the Stream version with Spring Data and with JdbcTemplate, and list the rules callers must follow.
1Keeping Memory Flat
The first goal is to never hold more than a small window of rows in memory. There are two ways to get rows lazily. A database cursor keeps the query open on the server and the JDBC driver fetches rows in chunks, set by the fetch size, for example 1,000 rows at a time. Keyset pages run a fresh query for each page, such as WHERE id > :lastId ORDER BY id LIMIT 1000, and remember the last id between pages.
Notice that the JDBC driver must actually stream. PostgreSQL's driver only uses a server-side cursor when autocommit is off, which it is inside a transaction, and a fetch size is set; otherwise it reads the whole result into memory. MySQL Connector/J needs either useCursorFetch=true with a fetch size or the special fetch size Integer.MIN_VALUE. Check your driver's documentation, because the default in both is to read everything.
2Iterator and Iterable Cannot Say When They Are Done
Suppose we return a lazy Iterator backed by an open cursor. If the caller reads to the end, our hasNext() can see that there are no more rows and close the cursor. But the caller might stop early: it finds what it wanted after 10,000 rows, or an exception is thrown while writing the export file. Iterator has no close() method, so the caller has no way to tell us, and the cursor and its connection stay open.
Iterable is no better and adds a second problem. Its contract suggests we can call iterator() again to iterate a second time, which for a database query means running the query again, silently and expensively. We could add a custom close() to our own type, but callers using the standard interfaces will not know it is there, and the enhanced for loop never calls it.
3Stream Makes Cleanup Explicit
Stream extends BaseStream, which extends AutoCloseable. We register cleanup with onClose(), and when the caller uses try-with-resources, close() runs whether the caller finishes, stops early or throws. That is exactly what Iterator could not express.
| Type | Lazy | Early-exit cleanup | Single-use is clear |
|---|---|---|---|
Iterator<T> | Yes | No close method: leaks | Somewhat: one pass by nature |
Iterable<T> | Yes | No close method: leaks | No: suggests re-iteration |
Stream<T> | Yes | onClose + try-with-resources | Yes: reuse throws IllegalStateException |
In real code we rarely write this by hand. JdbcTemplate.queryForStream(sql, rowMapper) returns a Stream that closes its JDBC resources when the stream is closed, and Spring Data repositories can declare Stream<T> as a return type.
4Spring Data Streams and the Transaction
A Spring Data JPA repository can return a Stream directly. Spring Data requires the stream to be consumed inside a transaction, because the open cursor lives on the transaction's connection; calling a streaming query method without one throws InvalidDataAccessApiUsageException.
There is a catch with JPA. Every entity loaded is also kept in the persistence context, the first-level cache of the current transaction, so after 50 million rows we would hold 50 million entities anyway. Detaching each entity after use, clearing the entity manager every few thousand rows, or selecting a DTO projection instead of entities keeps memory flat. Check the hint constant for your Hibernate version; in Hibernate 6 and 7 it is HibernateHints.HINT_FETCH_SIZE, whose value is org.hibernate.fetchSize.
5Rules to Document for Callers
Whichever type we choose, the method's contract must say three things. The result is single-use: it is backed by one cursor and cannot be read twice. It must be consumed inside the transaction that opened it, so it cannot be returned from a service method annotated with @Transactional and used later in the controller. And it must be closed, which for a Stream means try-with-resources.
If we do write our own Iterator for some part of this, hasNext() must be idempotent: calling it twice in a row must not advance the cursor and lose a row. The usual way is to fetch the next row into a field on the first hasNext(), return true while that field is filled, and clear it in next().
6Follow-up questions
Why not return a Page or a List of 1,000 rows at a time?
That is a valid design, and it needs no open resource between calls, which makes it the better choice across process boundaries such as a REST API. Inside one process, the caller would have to loop over pages itself, so a Stream that pages internally is more convenient. With offset paging, rows shift if data changes during the export, so keyset paging is safer.
Is a parallel stream a good idea here?
Usually not. A ResultSet is read sequentially by one connection, so the source cannot be split efficiently, and the parallel stream would mostly buffer rows. If export throughput matters, split the work by key ranges and run several independent streams instead.
What happens if the caller forgets try-with-resources?
The stream is never closed, so the cursor and connection stay open until the transaction ends, when Spring releases the connection. In a long-running method that can still exhaust the pool. Static analysis tools flag unclosed AutoCloseable resources, which is another advantage of returning a Stream.
7Conclusion
In this answer, we saw that a lazy result backed by a cursor or keyset pages keeps memory flat whichever type we return, but Iterator and Iterable have no close method, so callers who stop early leak cursors and connections, and Iterable even invites re-running the query. A Stream with onClose, used in try-with-resources, makes cleanup explicit. Spring Data streams must be consumed inside a transaction, the JPA persistence context must be kept small, a hand-written hasNext must be idempotent, and the result must be documented as single-use.
Open with
For 50 million rows the first requirement is laziness: I'd back the result with a database cursor using a fetch size like 1,000, or with keyset pages, so only a small window of rows is in memory.
Then, if they want more
Any of the three types can be lazy, so the real difference is cleanup. Iterator and Iterable have no close method. If the caller stops early, say after a break or an exception, there's no way to tell me, so the cursor and its connection stay open and eventually exhaust the pool.
Iterable is worse because it suggests you can iterate again, which would re-run the query. A Stream implements AutoCloseable, so I register cleanup with onClose and require the caller to use try-with-resources, and cleanup happens even with limit or an exception. In Spring I'd use a Spring Data repository method returning Stream with a fetch-size hint, or JdbcTemplate.queryForStream.
Spring Data requires the stream to be consumed inside a transaction, because the cursor lives on that connection, so the export method is @Transactional(readOnly = true). With JPA I'd also detach or clear entities as I go, or select a DTO projection, so the persistence context doesn't grow to 50 million entities.
I'd document that the result is single-use and must be consumed and closed inside the transaction. And if I hand-write an iterator anywhere, hasNext must be idempotent, so calling it twice never skips a row.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Hibernate 6
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Collections Framework, overview, java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "You want to expose a repository method that returns all rows of a 50-million-row table...": https://scrivio-interview-library.netlify.app/java/iteration/9cdec2567c/