Video in progress
A batch job processing a million rows with Hibernate fills the heap and crashes with an OOM. How do you analyze and fix it, from the JVM side and the code side?
The usual cause is the persistence context: every loaded entity and its snapshot stay in memory until the session closes. In a heap dump or histogram you see EntityEntry and the entity classes. The fix is working in chunks with flush()/clear(), StatelessSession, reading with scroll/stream, or a DTO projection.
📖 Answer
The typical code:
@Transactional
public void reprice() {
List<Product> all = repo.findAll(); // 1 million entities at once
for (Product p : all) p.setPrice(calc(p));
}
One transaction, one EntityManager. For every entity Hibernate keeps: the object itself, a copy of the initial state for dirty checking (Object[]), an EntityEntry, and an identity map entry. If one entity is 1 KB, it takes 2-3 KB in memory. For a million rows that is several GB, and all of it is alive, so the GC can do nothing.
To confirm:
jcmd <pid> GC.class_histogram | head -20
# com.acme.Product, org.hibernate.engine.internal.EntityEntryContext$ManagedEntityImpl,
# java.lang.Object[] are at the top
And in the GC log, Old grows after every GC and at the end you get "GC overhead" or "Java heap space".
The fix options:
try (Stream<Product> s = repo.streamAll()) { // with a fetch size, @QueryHints
int i = 0;
for (Product p : (Iterable<Product>) s::iterator) {
p.setPrice(calc(p));
if (++i % 1000 == 0) { em.flush(); em.clear(); }
}
}
hibernate.jdbc.batch_size=50andorder_updates=true, so the UPDATEs go out in batches too;- for streaming to work in PostgreSQL you need a fetch size and a transaction without autocommit, otherwise the driver still pulls everything into memory;
StatelessSession: no persistence context at all, no dirty checking, and you write with an explicitupdate();- the cheapest is often a single SQL statement:
UPDATE product SET price = ..., never bringing the data into the JVM at all.
If you use Spring Batch, the chunk-oriented step gives you exactly this pattern. Raising the heap is not the fix here: tomorrow there will be two million rows.
Sign up to mark studied questions and save your progress.