I'm looking for a best practice for ensuring that session access is threadsafe. Something that is scalable and works in a clustered environment.
Servlet 2.5 MR6
"Multiple servlets executing request threads may have active access to the same session object at the same time. The container must ensure that manipulation of internal data structures representing the session attributes is performed in a threadsafe manner. The Developer has the responsibility for threadsafe access to the attribute objects themselves. This will protect the attribute collection inside the HttpSession object from concurrent access, eliminating the opportunity for an application to cause that collection to become corrupted.
As the Developer responsible for maintaining threadsafe access to the attribute objects, what can I use as a mutex object to synchronize on?
Head First... recommends synchronizing on the
HttpSession, but there are no guarantees that
HttpServletRequest.getSession() will return the same object each time. The spec doesn't prohibit the container from returning a new wrapper to an underlying collection for each request.
Are there any known containers in which this code is not valid?
Should I be synchronizing on an attribute? That is, a
Serializable attribute placed there by a
HttpSessionListener like so:
If the session is maintained in memory (and this would be required to maintain non-
Serializable objects) then this should be adequate. If attributes were serialized on
setAttribute and deserialized on
getAttribute (the spec doesn't prohibit it), then this would not work. Are there any known containers that behave like this?
I can see how to manage a mutex object external to the session using lifecycle listeners and the session ID, but is that overkill?