是否每个 HTTP 请求访问同一个 servlet 对象但在不同的线程中?还是创建新线程和新 Servlet 实例?
最佳答案
如果您的 servlet 未实现 SingleThreadModel
,容器将使用相同的 servlet 实例。
否则无法保证命中相同的 Servlet
对象。如果认为有必要,容器可以自由创建更多的 servlet 实例。但是请求来自不同的线程,不一定是新创建的(正如 Sanjay 提到的)。
来自 Servlet 3.0 规范:
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.
...
Generally the Web container handles concurrent requests to the same servlet by concurrent execution of the service method on different threads.
关于java - 每个请求是否访问同一个 servlet 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12509830/