Basically, how long is an instance of a servlet around for? I am kind of guessing it is session scope. However, I suppose it could have some sort of timeout or garbage collection to remove old instances.
life cycle of servlet > 1) load the class. 2) instantiate the servlet. 3) servlet container construct the servlet config interface. 4) container call the init() and pass the servlet config object. 5) httpRequest and httpResponse object created.
The servlet life cycle is made up of four stages: Instantiation. Initialization. Client request handling.
The lifecycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps. If an instance of the servlet does not exist, the web container: Loads the servlet class.
An HTTP servlet is a special type of servlet that handles an HTTP request and provides an HTTP response, usually in the form of an HTML page.
load-on-startup
setting)init()
method of the servlet is calledservice()
method being called by multiple threads). That's why it is not advisable to have any synchronization in it, and you should avoid instance variables of the servletdestroy()
method is called.The lifecycle is well defined, and exposed through lifecycle methods exposed in init, service, and destroy methods of the Servlet.
And, despite what else is being said here, this is all you can count on from the specification. Basically, you get those three methods and a guarantee that Servlets are not thread safe. That a single servlet MAY be simultaneously accessed by one or more requests.
There is nothing in the specification that limits a servlet to one instance the container, if a container decides to, it can get a request, create a servlet, call it's init, then service, then destroy methods, and set it free for garbage collection.
Individual containers have potentially different implementations.
Most containers do create a single instance. But the specification does not guarantee that, so you shouldn't rely on it.
Also, consider something like Google App Engine. GAE is VERY aggressive is continually expiring and shutting down entire web apps that receive no traffic. If you have a lightly traveled site, you can very well expect the entire app to start up, init all of its services, init any load-on-startup servlets, execute the request, and then shut everything down. So, on GAE it's imperative that you have a very fast application startup in order to maintain any semblance of performance.
So, simply, what you can count on is what the specification says. Individual containers may offer different run time experiences.
A Servlet lives as long as the application does.
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