Java Servlet Context and Session level variables
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 varia开发者_如何学编程bles or I have got in completely wrong?
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.
After a reading a bit (amongst others this bug fix) I do get the strong impression that sessions are thread-safe, or should be.
you know all context variables are thread unsafe, except local, so if you are trying to access/modify this context variables use locks, in java it is synchronized
objects, for more info read Head First Servlets & JSP - Chapter 5. Good luck!
精彩评论