0

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?

Navigateur
  • 1,852
  • 3
  • 23
  • 39
  • possible duplicate of [How do servlets work? Instantiation, session variables and multithreading](http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-session-variables-and-multithreading) – BalusC Sep 08 '11 at 16:49
  • related: http://stackoverflow.com/questions/3894088/what-is-the-lifecycle-of-a-httpservlet/3894152#3894152 – Bozho Sep 08 '11 at 16:51

2 Answers2

3

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
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • I'd add that it's not guaranteed to be the same instance throughout the lifetime of the application, AFAIK. – Dave Newton Sep 08 '11 at 16:54
  • @Dave: only if it implements the since Servlet 2.4 (2003) **deprecated** `SingleThreadModel` which nobody should ever use nowadays. – BalusC Sep 08 '11 at 16:56
  • 1
    Is that in the spec? I haven't looked for awhile, but I don't recall seeing anything that would prevent a container from destroying a servlet instance and spinning up a new one. – Dave Newton Sep 08 '11 at 17:10
  • in a non-clustered environment it is in the spec, as far as I remember – Bozho Sep 08 '11 at 17:16
0

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.

Dan
  • 11,077
  • 20
  • 84
  • 119