java - 多个线程怎么可能只有一个servlet实例?

标签 java multithreading tomcat servlets

<分区>

通常,容器中只有一个特定 servlet 的实例。每个请求都会重用此 servlet。但是,默认情况下,每个 servlet 请求都在不同的线程中运行。比方说,在对 doPost(request, response) 的两次不同调用中,怎么可能只存在一个扩展 HttpServlet 的 servlet 实例?

我想确认是否有两个堆栈为此使用一个堆。

最佳答案

Servlet Specification #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 (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/

相关文章:

java - 异步和同步模式的并发

ios - 如何在 `init` 中初始化线程安全变量?

tomcat - 为什么传递依赖不包括我的最终 war ?

java - 线程池中的线程局部内存泄漏

java - 需要将下划线分隔的单词转换为人类可读的形式吗?

java - JComboxBox setSelectedItem

java - POM 文件中占位符的值?

java - TimerTask与Executors.newScheduledThreadPool的区别(一)

java - 日志4j2。无法在 zk/tomcat 6 web 项目上配置和运行

java - 使用 java.util.Map 时出现编译问题