views:

73

answers:

2

Hello,

I am using thread local to manage my hibernate sessions. Recently I have been seeing OutOfMemory exceptions on my production server. I ran Eclipse MAT on the heap_dump and saw a lot of my sessions are not getting garbage collected even though they are being closed due to them being referenced by tomcatse ThreadWithAttributes object. This is driving me crazy right now I have seen a lot of posts with similar questions on different forums but no answers. Any assistance will be greatly appreciated.

Thanks

A: 

If your are using Hibernate Sessions in a web application, DON'T let the Session objects in ThreadLocal stay there across requests - since you have no control over the threads anyway, they belong to the container.

If you need to create and close a Session for the lifetime of a web request, and you don't want to pass the Session object around everywhere, you should consider writing a ServletFilter to handle the cleanup - it will get invoked around every request. You could also let that filter commit or rollback any transactions you may have started.

You should read this page for a simple recipe to how to do it: http://community.jboss.org/wiki/OpenSessioninView

JesperSM
A: 

Hi, thanks for your reply. I am currently using open session in view, using getCurrentSession() which means that the session is per request cand closes on transaction.commit(). I can see that the sessions are being closed (though not nulled out) yet somehow the ThreadWithAttributes tomcat class hold a reference to the sessionImpl preventing it from being garbage collected. This happens with every thread. My database is pretty large so this cause out of memory errors after a few hours or a day at most and the server needs to be bounced.

tiffany