Suppose i configure my web.XML such that my servlet is loaded during the server start up,
does the servlet instance live till the server stops or does the servlet instance is killed after a specific amount of time without any request and waits for a new request to create a new servlet instance.
i know there will be only one servlet instance per application but i want to know the lifetime of a servlet instance.
Also, I don't think that the spec requires that there only be a single servlet instance. Again, that's the common case, but I think the container is free to create several instances that exist simultaneously.
The lesson is: don't assume that the "init" method is only called once during the lifetime of a web app, and make sure that everything permanent that it sets up is torn down in the "destroy" method.
so you mean that servlet init method may call more than once ,it depends on container right?
Yes. Of course, the init method of any particular servlet instance will only be called once, as per the Servlet interface documentation.
surprised to know that there would be more than one server instances for a servlet.
Not necessarily would - but potentially could.
[ November 11, 2008: Message edited by: Ulf Dittmer ]
Each time a servlet is put into service, its init method will be called.
From the servlet spec:
SRV.2.2 Number of Instances
The servlet declaration which is part of the deployment descriptor of theWeb application
containing the servlet, as described in Chapter SRV.13, �Deployment
Descriptor�, controls how the servlet container provides instances of the servlet.
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 (JVMTM). 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
[ November 11, 2008: Message edited by: Ben Souther ]
Originally posted by Ben Souther:
Init is called only when a servlet is put into service.
But ben, i am confusing when the servlet is put into service? actually what is the servlet is put into service?
i think when ever new instance created then servlets init call. that mean "the servlet is put into service=new instance created"
Once in service, your servlet is ready to handle any incoming requests.
If you haven't already, you should read the Servlet spec (link in my signature). In particular look at SRV 2.3 which covers the servlet life cycle.