[Logo]
Forums Register Login
HttpSession and concurrent access
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?
 

Originally posted by Alwin McDonnell:

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?



There is often need to serialize objects, even in containers that store session data in memory. Tomcat for instances serializes sessions to disk when an application is shut down or reloaded. It also serializes them for session replication over TCP in a clustered environment.

A good rule of thumb is to always make sure that any object bound to session scope implements Serilizable.
Why is the word "abbreviation" so long? And this ad is so short?
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA


This thread has been viewed 3659 times.

All times above are in ranch (not your local) time.
The current ranch time is
Jul 22, 2018 03:12:14.