根据 java 文档,它说如果使用 SingleThreadModel,则有两种方法可以创建和使用 servlet 实例 1.创建一个servlet实例,并使service()方法同步,这样就只允许一个线程执行service方法。 2. 创建一个 servlet 池并为每个请求使用池中的一个 servlet 实例来处理请求。
我想问的问题是,我还阅读了为每个请求创建和销毁一个新的 Servlet 实例。现在哪个是正确的
最佳答案
这是规范的内容(3.0 版,第 2.2 节):
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 (JVMTM)1. 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.
请注意,您真的不应该使用单线程模型。只需确保您的 servlet 是 thread-sae。 servlet 通常是无状态的,因此您无需执行任何操作即可使其成为线程安全的。
关于java - 使用SingleThreadModel时servlet的生命周期管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22772961/