Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call destroy() in servlet from eclipse?

When I shutdown server, destroy() is not called in Eclipse.

public class Demo extends GenericServlet {

    public void init(ServletConfig config) throws ServletException{
        System.out.println("intit intialized");
    }

    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        System.out.println("servicccceeeeeeeee method........");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.print("<h1>service method</h1>");
        out.close();
    }

    public void destroy() {
        System.out.printlnln(".........destroy method invoked.......");
    }

}

When and how do I call the destroy method?

like image 958
anand kumar Avatar asked Dec 19 '22 01:12

anand kumar


2 Answers

It won't be invoked when you abruptly terminate the whole Java Virtual Machine altogether. I.e. when you press the red square button in Eclipse's Console tab.

enter image description here


It will be invoked when you gently stop or restart the server itself. I.e. when you press the red square button in Eclipse's Servers tab.

enter image description here

like image 65
BalusC Avatar answered Dec 30 '22 21:12

BalusC


In Eclipse, destroy() is called only if you gracefully shut down your application. If you kill it with the stop button, or if you unplug power supply to your computer destroy() will not be called.


And now more about the method itself:

Servlet.destroy()'s javadoc says:

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. This method gives the servlet an opportunity to clean up any resources that are being held (for example, memory, file handles, threads) and make sure that any persistent state is synchronized with the servlet's current state in memory.

It doesn't specify what situations would cause a servlet to be "taken out of service", it is simply an event to which you can react to if you need to. So in destroy you should clean up your Servlet if there is anything to clean up, you could store the state of the Servet, and perhaps log the error. It could happen, for example, because Server was out of memory.

like image 29
darijan Avatar answered Dec 30 '22 20:12

darijan