If a servlet is not thread safe, then does that mean that all objects created and referenced during the servlet lifecycle are not thread safe? Maybe I'm not quite getting this, but in Web applications you almost always want to account for data stored during the servlet lifecycle that is pertinent to a single user's request. What are some of the best practices for managing this data? Should I instantiate a processor (much like a front controller) for my servlet, and wrap it in a synchronized block? This seems like it would be a major performance issue.
views:
38answers:
2
+2
Q:
What are some thread safe techniques for storing data about a single user's request in a servlet?
+3
A:
Just don't assign request or session scoped data as instance variable of the servlet. That's all. Declare and assign them inside the method block and it will be threadsafe (read: it won't be shared among all requests/threads anymore). I've answered this in detail before here: In Java, How do I make sure my web application is thread safe?.
BalusC
2010-02-27 23:28:21
+1
A:
Instance variables are not thread safe. Local variables (declared within the methods) would be thread safe; each thread essentially has its own set of local variables.
See this JavaWorld article on writing thread-safe servlets for additional tips if you MUST rely on an instance variable.
marklai
2010-02-27 23:32:18