I have experimented the inconsistency when multiple threads access/modify context variables but could not produce the same behaviour at session level. For example calling session.setAttribute("something") method within the service method does not cause race-condition when two requests (which means two threads) for same sessionid come in. Is it because Tomcat provides thread safety for session variables or I have got in completely wrong?
- I doubt very much that tomcat provides any thready safety. How are you testing accessing session attributes in a multithreaded way? I know that using random numbers isn't the best way of testing something but when I test multithread issues I always sleep my threads for a randon amount of time (usually a few seconds) prior to calling the code in question. Just a thought.hooknc– hooknc2011-03-26 16:06:13 +00:00Commented Mar 26, 2011 at 16:06
- Not a great way, wrote a small program that is sending same session id. I cannot seem to find any resources saying thread safety of session variables is developer's responsibility but all of the discussions do advise for application level variables though.Abidi– Abidi2011-03-26 16:29:08 +00:00Commented Mar 26, 2011 at 16:29
3 Answers
Servlet spec ver 3.0 explicitly states that access to session keys is thread-safe, in section 7.7.1. However, access to elements stored under these keys isn't thread-safe. Thread safety in this case must be ensured by application developer.
7.7.1 Threading Issues 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 thread safe manner. The Developer has the responsibility for thread safe 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.
Sample code to illustrate this:
HttpSession session; List items; session.put("cart", items); // thread1 writes cart reference to session, this is thread-safe ... items = session.get("cart"); // thread1 reads cart reference from session, this is thread-safe items.get(0); // access to elements of application collection is *not* thread-safe, you must use explicit synchronization here. I believe what is meant here by "thread safe manner" is that HttpSession access methods are guaranteed to be thread-safe, but all access to elements stored in session by methods of these elements is not guaranteed to be thread-safe.
4 Comments
After a reading a bit (amongst others this bug fix) I do get the strong impression that sessions are thread-safe, or should be.