tags:

views:

1138

answers:

2

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.

+2  A: 

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.

Rob H
It "fixed" the problem :)As you suggested, we are reviewing some of our "HibernateUtils" created to see where we're holding on to session references.
StudioEvoque
You might also want to consider using a framework like Spring to manage your Hibernate sessions and transactions for you if you're not already.
Rob H
A: 

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 ;)

David Taylor
If explict GC does not help, the objects must still be referenced somewhere in your code. A profiler with memory leak detection is the fastest path to an answer IMHO since you will *see* path causing the leakage. Best of luck!
David Taylor