I am going through the book for "Java Web Services: Up and Running, 2nd Edition" and came across a statement that says:
A web server such as Tomcat can instantiate arbitrarily many instances of a servlet, although the number is typically small (e.g., 1 through 4). The web server itself makes the decision.
So it means if I create a servlet then the server can create more than 1 instance but this is in contradiction to the explanation given in many posts for example if I check in this post : "10 clients requests for a Servlet.How many servlet instances are created" then it clearly states that:
Only one instance of servlet exist (per classloader) , and each request will be served on its own thread
So please help me in understanding this, does a server can create more than 1 instance for a servlet?
Usually only one instance of the Servlet object is created. But some advanced containers might create more than one instance under certain circumstances. Even so, there is a difference between static class variables and instance variables.
2) Servlet instance is created The servlet instance is created only once in the servlet life cycle.
When a single-threaded servlet is deployed to the Sun Java System Web Server, the servlet engine creates a servlet instance pool used for incoming requests (multiple copies of the same servlet in memory).
You are right, Only single instance of Servlet is created, but that instance is shared across multiple threads.
The Servlet Specification states
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.In the case where a servlet was deployed as part of an application marked in the deployment descriptor as distributable, a container may have only one instance per servlet declaration per Java Virtual Machine (JVM). However, if the servlet in a distributable application implements the
SingleThreadModel
interface, the container may instantiate multiple instances of that servlet in each JVM of the container.
So it depends how you are deployed.
As suggested in the comments, SingleThreadModel
has been deprecated for a long time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With