Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force hibernate to release memory once the session is closed?

Tags:

java

hibernate

We've just recently started using Hibernate and are still getting used to the way it works.

On of the things we've seen is that even after all sessions are closed and references have gone out of scope, hibernate still seems to maintain the previously used database values in it's cache.

We have code that reads from a set of tables in multiple passes. Because all the memory is freed very sparingly, the later passes slow down to a crawl.

Is there any way to force Hibernate to clear its cache ?

An explicit call to System.gc() doesn't help. (Yes, I know it is a suggestion)

Additional Info: We've explicitly disabled the second-level cache.

like image 942
StudioEvoque Avatar asked May 29 '09 22:05

StudioEvoque


2 Answers

You could try calling Session.clear to force a clear of the first-level cache. Be sure to call Session.flush first to write any pending changes to the database. If that "fixes" the problem, then I suspect something is still holding a reference to the session, preventing the objects in the cache from being garbage-collected. You may need to obtain a heap dump of your program to track down the leak.

like image 138
Rob H Avatar answered Oct 30 '22 15:10

Rob H


Hibernate also has an optional second level cache which could be at play. I agree with Rob, the easiest way to find out is to see what is still in memory after the session ends.

My current favorite tool for this is YourKit which is commercial and not exactly cheap. They used to offer (and may still offer) a personal license option which was very inexpensive ($99 IIRC). I have used YourKit for precisely this task when troubleshooting heap usage problems with Alfresco ECM. There are other tools available (e.g. CodeGear JGears) which I understand also work very well.

You might consider using a product in evaluation mode - if this finds your problem it might earn its keep ;)

like image 22
David Taylor Avatar answered Oct 30 '22 13:10

David Taylor