Stream rather than materialize: read with a scrollable cursor or keyset paging, set a fetch size so the driver does not buffer everything, and process in chunks with a commit per chunk. If you use JPA, clear the persistence context between chunks or use a stateless session, otherwise every entity stays in the first level cache. Batch the writes with JDBC batching, and make the job restartable from its last committed chunk.
Why interviewers ask this
Batch work is where JVM memory behavior and persistence context behavior become obvious, so this tests practical experience rather than theory. The interviewer wants streaming, chunked commits, persistence context clearing and restartability. Knowing that a JDBC driver may buffer the whole result set regardless of your code, unless the fetch size and transaction settings are right, is a strong signal.
How to structure your answer
- Rule out loading everything: stream or page the read.
- Explain fetch size and driver buffering behavior.
- Handle the persistence context so entities do not accumulate.
- Add chunked commits, batched writes and restartability.
Example answer
The core rule is that no step holds twenty million of anything. I read with keyset paging on the primary key, or a scrollable cursor with an explicit fetch size, and it is worth knowing that some drivers ignore that and buffer the entire result set unless you also run inside a transaction with autocommit off, which people discover the hard way when the heap fills before any processing starts. Then I process in chunks of a few thousand, write with JDBC batching so it is one round trip per chunk rather than per row, and commit per chunk. With JPA the extra trap is the persistence context: every entity read stays managed, so memory grows and flushes get slower as dirty checking walks more objects. I clear it every chunk or use a stateless session. Restartability matters as much as memory, so the job records the last committed key, which means a failure at row eighteen million resumes rather than starting again. And I throttle it, because a batch job that saturates the database at two in the morning still hits whoever is awake.
Walking into this interview soon? GhostPilot listens to your live call, spots the question the moment it is asked, and puts a structured answer on your screen in real time. Try it on your next mock, or grab a $29 Session Pass, no subscription, for the real thing.
See how it worksFollow-up questions to expect
- Why does the persistence context slow down as it grows?
- How would you parallelize this safely across partitions?
- How do you make the transformation idempotent for a restart?
Related java developer questions
Your interviewer will ask their own version of this. Paste your actual job description into the free Question Predictor and get the 20 questions that role is most likely to ask, with what each one is really probing.
Predict my questions