java - 使用SingleThreadModel时servlet的生命周期管理

标签 java servlets

根据 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/

相关文章:

java - 在java中缓存方法的结果

java - 使用包含列表(映射)作为值的 Hashmap 处理文本文件 - 如何处理?

java - Tomcat - 上下文路径匹配究竟是如何工作的?

java - 使用 JTextField - Swing 中的路径打开 PDF 文件

java - 如何组织我的 servlet?

java - 关闭jvm后调用方法Agent_OnLoad

java - HttpServlet : Url that contains ID between resources

servlets - Struts2 操作与 Servlet 相比如何?

java - 如何在 spring 框架中编码 url?

java - 无法验证从 Android 应用程序获取的 id token