views:

38

answers:

2

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.

+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
+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