Does each request access the same servlet object?
Solution 1
The container will use the same servlet instance if your servlet don't implement SingleThreadModel
.
Otherwise there is no guarantee that the same Servlet
object 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).
From the Servlet 3.0 specification:
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.
...
Generally the Web container handles concurrent requests to the same servlet by concurrent execution of the service method on different threads.
Solution 2
Each HTTP request creates a new thread but accesses the same instance of the 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.
![KyelJmD](https://i.stack.imgur.com/hCOqW.jpg?s=256&g=1)
Comments
-
KyelJmD about 2 years
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 ?
-
Sanjay T. Sharma almost 12 yearsI'm pretty sure it doesn't really create a new thread always; more like picks up a free thread from an existing thread pool.
-
Adam Dyga almost 12 years@SanjayT.Sharma You are right, it's often done this way (for performance reasons), but this is implementation detail of application server/servlet container and your code should not depend on that