且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么Servlet中的实例变量不是线程安全的

更新时间:2022-03-03 08:24:32

你犯的错误就在这里:


因此,因为所有这些线程都为
ActionServlet创建了一个新的类实例,所以我在这里看不到任何问题。因为
的实例这些线程是彼此分开的。

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.

容器不会创建Servlet类的新实例对于每个请求。它重用了现有的一个。这就是为什么它们不是线程安全的。

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.

Stripes Action Framework为每个请求创建一个新实例,这样在该框架下就可以了。但是,例如,Struts 1遵循Servlet模型,并且不会为每个请求创建新操作。

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.