<分区>
通常,容器中只有一个特定 servlet 的实例。每个请求都会重用此 servlet。但是,默认情况下,每个 servlet 请求都在不同的线程中运行。比方说,在对 doPost(request, response) 的两次不同调用中,怎么可能只存在一个扩展 HttpServlet 的 servlet 实例?
我想确认是否有两个堆栈为此使用一个堆。
<分区>
通常,容器中只有一个特定 servlet 的实例。每个请求都会重用此 servlet。但是,默认情况下,每个 servlet 请求都在不同的线程中运行。比方说,在对 doPost(request, response) 的两次不同调用中,怎么可能只存在一个扩展 HttpServlet 的 servlet 实例?
我想确认是否有两个堆栈为此使用一个堆。
最佳答案
For a servlet not hosted in a distributed environment (the default), the servlet container must use only one instance per servlet declaration. However, for a servlet implementing the SingleThreadModel interface, the servlet container may instantiate multiple instances to handle a heavy request load and serialize requests to a particular instance.
In the case where a servlet was deployed as part of an application marked in the deployment descriptor as distributable, a container may have only one instance per servlet declaration per Java Virtual Machine (JVM). However, if the servlet in a distributable application implements the SingleThreadModel interface, the container may instantiate multiple instances of that servlet in each JVM of the container.
因此,不使用 SingleThreadModel 会成功。
此外,Creating Servlets指出
By default, servlets are not thread-safe. The methods in a single servlet instance are usually executed numerous times simultaneously (up to the available memory limit). Each execution occurs in a different thread, though only one servlet copy exists in the servlet engine.
因此,您应该根据自己的情况处理同步问题;
关于java - 多个线程怎么可能只有一个servlet实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25282442/