Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many instances are created for a HTTP servlet

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?

like image 555
Chaitanya Avatar asked Mar 20 '14 20:03

Chaitanya


People also ask

How many instances of servlet are created?

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.

How many servlet instances are created in the servlet lifecycle?

2) Servlet instance is created The servlet instance is created only once in the servlet life cycle.

What is the instance of servlet?

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

How many servlet instances are created when multiple requests arrive simultaneously?

You are right, Only single instance of Servlet is created, but that instance is shared across multiple threads.


1 Answers

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.

like image 86
Sotirios Delimanolis Avatar answered Oct 15 '22 11:10

Sotirios Delimanolis