Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shall we call the destroy() method from the init() and service() methods in Servlet?

Shall we call the destroy() method from the init() and service() methods in a Servlet? I got many confusing answers across the blogs.

As I understand it, when we call the destroy() method from the init() it should call and destroy the servlet, if we are going to override the destroy() in our servlet. Then the servlet will get destroyed.

Is the above understanding right?

like image 815
gaurav Avatar asked May 25 '11 17:05

gaurav


1 Answers

None of all is true.

The servlet's destroy() method is only called by the container whenever it's going to be shutdown. During container's shutdown all servlets will be destroyed. You should not call the method yourself. The destroy() method just offers you the opportunity to execute some code upon shutdown. For example, to close some external resources which were opened during init().

E.g.

private SomeExternalResource someExternalResource;

@Override 
public void init() {
    someExternalResource = new SomeExternalResource();
}

@Override
public void destroy() {
    someExternalResource.close();
}

You do not necessarily need to implement the method when you have nothing to clean up.

like image 99
BalusC Avatar answered Nov 01 '22 15:11

BalusC