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 have experimented the inconsistency when multiple threads access/modify context variables but could not
Share
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:
I believe what is meant here by “thread safe manner” is that
HttpSessionaccess 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.