As per the link http://www.xyzws.com/Servletfaq/when-is-destroy-of-servlets-called/20, one of the reason of calling destroy method is when the servlet hasn't got a request in a long time.
I was thinking there could be some pages that don't get called for a long time. So, does that mean destroy will be called and they will be no longer used?
Actually, I was asked this question in interview and he told me that destroy method will only be called when server is shut down.
Appreciate any help on this.
In java servlet, the destroy() method is not supposed to be called by the programmer. But, if it is invoked, it gets executed.
Can we call destroy() method from service() method in Servlet? Yes, again, you can call destroy() from within the service() as it is also a method like any other. Although still strange, this could make sense sometimes, as destroy() will do whatever logic you have defined (cleanup, remove attributes, etc.).
The servlet is initialized by calling the init() method. The servlet calls service() method to process a client's request. The servlet is terminated by calling the destroy() method.
The destroy method provided by the HttpServlet class destroys the servlet and logs the destruction. To destroy any resources specific to your servlet, override the destroy method. The destroy method should undo any initialization work and synchronize persistent state with the current in-memory state.
AFAIK,
In java servlet, destroy()
is not supposed to be called by the programmer. But, if it is invoked, it gets executed. The implicit question is, will the servlet get destroyed? No, it will not. destroy()
method is not supposed to and will not destroy a java servlet.
The meaning of destroy()
in java servlet is, the content gets executed just before when the container decides to destroy the servlet. But if you invoke the destroy()
method yourself, the content just gets executed and then the respective process continues. With respective to this question, the destroy()
gets executed and then the servlet initialization gets completed.
destroy()
method is invoked first, then Servlet is removed from the container and then eventually garbage collected. destroy()
method generally contains code to free any resources like JDBC connection that will not be garbage collected.
Couple of cases :
As per the Doc
Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. This method is only called once all threads within the servlet's service method have exited or after a timeout period has passed. After the servlet container calls this method, it will not call the service method again on this servlet.
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