Search code examples
javaservletsclientinstancelifecycle

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


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?


Solution

  • 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.