First, the container is started (such as Tomcat) and it creates and initializes any servlets that are deployed within it. Once initialized, a servlet can respond to various requests through execution of the doGet and doPost methods. I believe this information is accurate, but let me know if I've got this wrong.
My question is, when is the destroy() method invoked? I'm guessing that this is invoked when the container is shut down. Or, possibly, is it invoked when the servlet is done processing all active requests. If that's the case, though, then wouldn't the container have to create a new servlet any time a request came in for a servlet that wasn't currently handling a request?
Anyway, the text is very good about explaining the life cycle and that, some time after the servlet has been initialized and has responded to one or more requests, it is destroyed (well, the destroy method is invoked, anyway - whether or not it's actually GC'd is another story). However, the text never explicitly says under what conditions destroy is invoked.
Originally posted by Bryan Basham:
So, can anyone guess why a container would destroy a servlet?
The servlet starts life when the Container finds the servlet class file. This virtually always happens when the Container starts up (for example, when you run Tomcat). When the Container starts, it looks for deployed web apps and then starts searching for servlet class files. (In the Deployment chapter, we'll go into more details of how, why, and where the Container looks for servlets.)
According to my minimum knowledge servlet is alive as long as application is alive. If I shut down the webserver, then the servlet is destroyed same as when i redeploy the application.
The only reason I can think of to destroy a servlet would be to free up memory, in the case that the system was running low
I'm guessing that when servlets are initialized it entirely up to the Container being used and is not standardized from one Container to the next. So, while Tomcat might initialize servlets when it is started, WebSphere might wait until the first request for a servlet to initialize it or it might initialize servlets based on information in the DD.
If there are truly multiple instances of a servlet being used, what are the implications of that to your code? Might you have problems sharing information between requests via servlet instance variables? (Although I'm not sure that's the best way to do it, anyway.)