Calling servlet's destroy method

Anand picture Anand · Nov 18, 2012 · Viewed 25.2k times · Source

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.

Answer

Bhavesh Shah picture Bhavesh Shah · Mar 19, 2013

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.