开发者

How long can a Java servlet instance be expected to persist? Does the same instance serve all clients? Can there be multiple instances?

开发者 https://www.devze.com 2023-04-03 19:03 出处:网络
I\'m 开发者_如何学JAVAtrying 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

I'm 开发者_如何学JAVAtrying 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?


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:

  • if you need something per-request, store it as a request attribute
  • if you need something global, store it as ServletContext attribute


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号