Why instance variable in Servlet is not thread-safe [duplicate]

為{幸葍}努か 提交于 2019-11-30 07:29:36
Will Hartung

The mistake you are making is here:

So, because all these threads create a new class instance for ActionServlet, so I don't see any problem here. because instances of these thread is separate of each other.

The container does not create a new instance of the Servlet class for each request. It reuses an existing one. This is why they are not thread safe.

The Stripes Action Framework DOES create a new instance for each request, so that's an okay assumption under that framework. However, for example, Struts 1 follows the Servlet model and does not create a new action per request.

That does not mean that the container is limited to a single instance, it in theory can create more than one, but it's not a specified behavior so can not be relied upon. Most of the popular ones do not.

because all these threads create a new class instance (action.java), so I don't see any problem

You are supposing that every thread create a class instance that will be used only by that thread, that's why you don't have any problem.

But try to imagine, with your specific sample, that the same instance is accessed from two threads. What's happend if both use in the same time your request and response members? Maybe you will read data from unidentifiable request, and you will write an inconsistent response that mix two parts.

So in you case too, instance variable are not thread safe, because if two thread access the same instance they can disturb each other.

The thing is, your action.java isn't instantiated always but it is being taken from an instance pool, the same goes for the request threads, they are been taken from a thread pool, so a servlet instance may be shared by multiple requests.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!