Invoking destroy() method of a servlet explicitly?

In this post, you will learn:

  • Can destroy() method be invoked explicitly?
  • If yes then what will be the consequences?
  • If not then why not?

Can destory() method of a servlet be invoked explicitly?

This is the most tricky question which is asked in interviews. Usually following answers are given of this question:

1. destory() can’t be invoked explicitly, it can only be invoked by the server.

2. The servlet will be destroyed abruptly i.e. the client will receive no response and the servlet will not be available for processing the subsequent requests.

3. In each request a new servlet object will be created and destroyed because of the explicit invocation of the destory() method.

All these answers are wrong and represents ignorance of the concept. The purpose of the destroy() method is not to destroy the servlet but to perform clean up operations. It can be thought of as the last wish of a servlet which the server has promised to fulfill before destroying the servlet.

The servlet object is created by the server hence it can only be destroyed by it. We can’t destroy a servlet in any way but we can fulfill its last wish i.e. we can invoke the detroy() method explicitly. If this method is invoked explicitly from the doGet(), doPost() or service() method the method will execute but the servlet object will remain as it is.

Following analogy will explain this concept. Lets assume that one day you heard your father asking your mother what is her last wish? Your mother replied that she wants to be wrapped in a banarasi saree on the death bed. Next day, you brought a banarasi saree. What does it mean? Do you want to kill your mother? Of course not, you just wants to be a good son! You know that your father will fulfill her last wish, there is no doubt about it. In addition to your father you also want to fulfill her last wish hence you brought the saree.

Now just assume that your father is the server, your mother is the servlet, destroy() method is the banarasi saree and you are the doGet() or doPost() method. The light of the concept will dawn on you and every thing will fall in place.

In the following practical example, I have demonstrated that we can invoke the destory() method, any time we wish without destroying the servlet because we can’t destroy it. The servlet is immortal from a programmer’s point of view.

Practical proof of explicit invocation of destroy() method:

First, the single line index.html :

Immortal servlet: which invokes destory() but isn't destoryed.

Second, the ImmortalServlet :

package com.techmentro.learningpad;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ImmortalServlet extends HttpServlet
{
	
	public void init()
	{
		//this method is invoked by the init(ServletConfig config) method of GenericServlet
		System.out.println(getServletConfig().getServletName()+" is initialized.");
		//this message is displayed along with servlet name to find out whether the object is created again after destruction.
		
	}
	public void doGet(
			HttpServletRequest request, 
			HttpServletResponse response)
			throws ServletException, IOException {
		
		//A message is displayed on the console to find out that this method is invoked.
		System.out.println("doGet() of "+getServletConfig().getServletName()+" is invoked.");
		//Invoking the destroy() explicitly.
		destroy();
		//Execution of the rest of the method is the proof in itself that the servlet object isn't destoryed
		PrintWriter out=response.getWriter();
		out.println("<b> Destroy invoked once, Servlet is still alive.</b><br/>");
		out.println("<b> Try again:<br/>");
		//Creating RequestDispatcher for index.html
		RequestDispatcher rd=request.getRequestDispatcher("index.html");
		//contents of index.html are included to faclitate invocation of doGet() again
		rd.include(request, response);
		
		
	}
	
	public void destroy()
	{
		//A message containing the servlet is displayed on the server console to find out when this method is invoked.
		System.out.println("Clean up operations are performed for  "+getServletConfig().getServletName());
		
	}

}


Third, the web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <servlet>
    <servlet-name>s1</servlet-name>
    <servlet-class>com.techmentro.learningpad.ImmortalServlet</servlet-class>
    </servlet>
  <servlet-mapping>
    <servlet-name>s1</servlet-name>
    <url-pattern>/immortalServlet</url-pattern>
  </servlet-mapping>
</web-app>

Output images of the practical example:

The print screen of home page.

home_page_explict_destroy

The print screen of response page.

response_page_explict_destroy

The print screen of server console.

console_output_explict_destroy

If you have understood the concept from this example then share it. let the correct knowledge spread…


Its time to recap the main concepts:

  1. The purpose of destroy() method isn’t the destruction of the servlet. It is used to free the resources which may be occupied by the servlet.
  2. A servlet can only be destroyed by the server when it is timed out or when the application is undeployed.
  3. destroy() method can be explicitly invoked.
If you like the post, then share it...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *