Java servlet 实例预计可以持续多长时间?同一实例是否为所有客户端提供服务?可以有多个实例吗?
我正在尝试了解 Java servlet 生命周期。
Java servlet 实例预计可以持续多长时间?这有多可靠?同一实例是否为所有客户端提供服务?或者同一 servlet 类的多个实例是否可以由不同的客户端生成?有没有一种方法可以强制保证同一个 servlet 实例永远存在(只要服务器打开)并且同一个 servlet 实例为所有客户端提供服务?或者已经保证是这样了?
I'm trying to understand the Java servlet life cycle.
How long can a Java servlet instance be expected to persist? How reliable is this? Does the same instance serve all clients? Or can multiple instances of the same servlet class be spawned by different clients? Is there a way of forcibly guaranteeing that the same servlet instance persists forever (as long as the server is switched on) and that that same servlet instance serves all clients? Or is that already guaranteed to be the case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
servlet 类只有一个实例,这是由规范保证的。
但是您不应该在 servlet 实例字段中存储任何内容。这至少不是线程安全的:
ServletContext
属性There is only one instance of a servlet class and that's guaranteed by the specification.
But you should not store anything in a servlet instance fields. This is not thread-safe at least:
ServletContext
attribute您有一个实例为该 Servlet 的所有请求提供服务。因此,它必须以可重入方式进行编程(它不是线程安全的)。
现在,您应该了解 servlet 中的线程如何工作以了解整个情况。
最初存在 SingleThreadModelInterface,但开发人员发现后已弃用序列化请求在性能方面并不是一个好主意;)
最后,Web 服务器通常有一个线程池,并且这些线程池在“每个连接线程”模型中回收。最近,这已被“每个请求线程”和异步处理所取代。
You have a single instance serving all requests to that Servlet. Therefore, it has to be programed in reentrant manner (it’s not thread safe).
Now, you should understand how threading in servlets work to understand the whole picture.
Originally existed SingleThreadModelInterface, but was deprecated once developers found out that serializing requests in not such a good idea performance wise ;)
Finally, web servers generally have a thread pool and these are recycled in “Thread per connection” model. Lately, this is being replaced with “Thread per request” and asynchronous handling.