java 每个请求是否访问相同的 servlet 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12509830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:10:39  来源:igfitidea点击:

Does each request access the same servlet object?

javahttpservletsrequest

提问by KyelJmD

Does each HTTP request access the same servlet object but in a different thread? or does it create a new thread and new Servlet Instance ?

每个 HTTP 请求是否访问相同的 servlet 对象但在不同的线程中?或者它是否创建了一个新线程和新的 Servlet 实例?

采纳答案by dcernahoschi

The container will use the same servlet instance if your servlet don't implement SingleThreadModel. Otherwise there is no guarantee that the same Servletobject is hit. The container is free to create more servlet instances if it considers necessary. But the requests comes on different threads, not necessarily newly created (as Sanjay mentioned).

如果您的 servlet 没有实现,容器将使用相同的 servlet 实例SingleThreadModel。否则无法保证Servlet命中相同的对象。如果认为有必要,容器可以自由创建更多 servlet 实例。但是请求来自不同的线程,不一定是新创建的(如 Sanjay 提到的)。

From the Servlet 3.0 specification:

来自 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.

对于不在分布式环境(默认)中托管的 servlet,servlet 容器必须在每个 servlet 声明中仅使用一个实例。但是,对于实现 SingleThreadModel 接口的 servlet,servlet 容器可能会实例化多个实例来处理繁重的请求负载并将请求序列化到特定实例。

...

...

Generally the Web container handles concurrent requests to the same servlet by concurrent execution of the service method on different threads.

通常,Web 容器通过在不同线程上并发执行服务方法来处理对同一 servlet 的并发请求。

回答by Marko Krajnc

Each HTTP request creates a new thread but accesses the same instance of the Servlet.

每个 HTTP 请求都会创建一个新线程,但访问 Servlet 的相同实例。

EDIT: In case of one server node, you will have the same Servlet instance on that node. In case of load balancing/many servers you will usually have one instance per Java VM.

编辑:在一个服务器节点的情况下,您将在该节点上拥有相同的 Servlet 实例。在负载平衡/许多服务器的情况下,您通常每个 Java VM 有一个实例。