Thursday, September 15, 2005

Normally only 1 instance of a servlet is created, but if we configure the web server to have multiple instance say 10 instances of a servlet A, then in that situation, how many times will the init() method be called? 1 or 10 times?


Each servlet put into service via a declaration will have its init method called with the servlet config containing any init params for that declaration.

Each servlet declaration gets its own instance of a servlet regardless of whether an instance of that same servlet has already been created as a result of a different servlet declaration.

Here's what the Servlet Spec (2.4) says:

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

the servlet container must use only one instance per servlet declaration

Hence if we have 10 servlet declaration of the same Servlet we have 10 instance of the same Servlet with every instance having their int() method called 0nce.

My web.xml :

servlet
servlet-name Ch3 Beer /servlet-name
servlet-class BeerSelect /servlet-class
/servlet

servlet-mapping
servlet-name Ch3 Beer /servlet-name
url-pattern /SelectBeer.do /url-pattern
/servlet-mapping

servlet
servlet-name Ch31 Beer /servlet-name
servlet-class BeerSelect /servlet-class
/servlet

servlet-mapping
servlet-name Ch31 Beer /servlet-name
url-pattern /SelectBeer1.do /url-pattern
/servlet-mapping


Note the items above bolded.They are different.When u access the servlet by using "/SelectBeer.do" one instance of "BeerSelect" will be created by the container.When u access the same servlet using "/SelectBeer1.do" another instance will be created.Console output is conforming the same!!

1 Comments:

Blogger specialistadhd said...

Hi, I was just blog surfing and found you! If you are interested, go see my attention deficit hyperactivity disorder related site. It isnt anything special but you may still find something of interest.

3:02 AM  

Post a Comment

<< Home