Hibernate out of memory exception while processing large collection of elements

You have confused flushing with clearing:

  • flushing a session executes all pending statements against the database (it synchronizes the in-memory state with the database state);

  • clearing a session purges the session (1st-level) cache, thus freeing memory.

So you need to both flush and clear a session in order to recover the occupied memory.

In addition to that, you must disable the 2nd-level cache. Otherwise all (or most of) the objects will remain reachable even after clearing the session.


I don't know why you think committing a transaction frees heap memory. Running garbage collection does that.

OOM error can happen if your perm gen is exhausted.

The easy answer is to change your min and max heap sizes and perm gen size when you start the JVM and see if it goes away.

I'd recommending getting a profiler, like VisualVM, and seeing what is consuming your memory at runtime. It should be easy to fix.

I'd guess that you're trying to commit too large a chunk at once. Break it up into smaller pieces and see if that helps.