Hibernate version: 3.2.0.ga
(My apologies if this has been discussed before. I did extensive searching and didn't find anything that quite answers my question. If there is something, pointers are very much appreciated.)
I'm new to Hibernate and am currently struggling with how to best integrate it into the servlet application that my team is currently developing. My specific dilemma at the moment is how to implement session-per-request with detached objects in a thread-safe manner.
Chapter 8 of the Hibernate in Action book discusses the issues of detached objects and thread safety. It gives the example of a user submitting a form twice, and I can think of several other scenarios which would cause two or more threads to access the HttpSession simultaneously. The book suggests a few solutions to this problem: rejecting additional requests if one is currently processing, serializing all requests from the same user by synchronizing on the HttpSession in a servlet filter, and finally maintaining a map of session information to separate windows in a multi-window application.
None of these solutions seem to be workable in my situation. I am using Tapestry, and taking advantage of its component-driven approach, therefore all of the CSS files and images in my application are classpath resources, and every request is going to be serviced by the servlet. The first two solutions aren't practical as even loading my application's login page will open at least 4 concurrent requests (two CSS files, several images, the HTML document, etc.) and if these requests are serialized I am of the opinion that this will noticeably impact perceived performance of the application and will impact scalability in the long run. The final solution (mapping between windows) doesn't solve the issue of users opening multiple tabs or windows as each window will have the same name/identifier.
So, I'm struggling to come up with a solution to this that doesn't require me to abandon detached objects. I have an idea for a solution, but it seems cumbersome and I was hoping to get some suggestions or feedback on this.
My idea is to explicitly synchronize only the sections of the code in my request action handlers that have to work with the potentially shared detached objects. My plan is to synchronize either on a mutex object, or one of the detached objects, and within the synchronized block update() the detached object, perform my model manipulations, commit the transaction, close the session, then end the lock. It would still be possible for more than one thread to share a given detached object, but this would prevent my code from attempting to attach the object(s) to more than one session simultaneously.
Can someone with a little more experience with this sort of thing give me some advice on this? Does this sound like a workable approach, or is there something better I can do? Any help or advice would be greatly appreciated.
|