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.
SCJP 1.5, SCWCD 1.4.
Hanging between Web Services and EJB
That's up to the servlet container. It can create and destroy servlet instances whenever it feels like it. The most common case is probably that one servlet instance gets created at startup and is then used until the web app stops, but that's not specified.
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.
Unless you're using the deprecated SingleThreadModel interface or hosting in a distributed environment, there will be only one instance of your servlet at a time. The container is free, however, to take a servlet out of service, and to put it back into service at any time.
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 container.
[ November 11, 2008: Message edited by: Ben Souther ]