开发者

What are some thread safe techniques for storing data about a single user's request in a servlet?

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.


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?.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜