我正在浏览 "Java Web Services: Up and Running, 2nd Edition" 的书并遇到了一个声明:
A web server such as Tomcat can instantiate arbitrarily many instances of a servlet, although the number is typically small (e.g., 1 through 4). The web server itself makes the decision.
所以这意味着如果我创建一个 servlet,那么服务器可以创建超过 1 个实例,但这与许多帖子中给出的解释相矛盾,例如,如果我查看这篇帖子:“10 clients requests for a Servlet.How many servlet instances are created”,那么它清楚地说明那:
Only one instance of servlet exist (per classloader) , and each request will be served on its own thread
所以请帮助我理解这一点,服务器是否可以为 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
已被弃用很长时间。
关于java - 为 HTTP servlet 创建了多少个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22544152/