Servlet destroy

Finalizing a servlet means that, we are calling the destroy () method. The destroy () method helps to remove the servlet from the service. We are calling the destroy () method of the Servlet interface, when a servlet container wants to remove the servelt from the service.

That is a container needs to recover memory resources, or it wants to being shutting down, the servlet container check the servlet is unplug or not. The servlet is in unplugging status, which means that servlet is not in the running state or servlet never provide any services. In the destroy () method we liberate or release all resources the servlet is using and save any persistent state.

The destroy () method helps to releases the database object created in the init () method. In the finalizing method first we are initialize the database objects and perform the needed services. After performing all the services, the container destroy that object by using destroy () method.

In the finalization process helps to learn about what happens when s servlet is going to be finalize. Due to the recovery of memory resources or on being shutdown, etc, a servlet container calls the destroy () method of Servlet interface when it found that the servlet should be deleted from the service () method. Once the servlet container calls the destroy () method servlet’s service () method should be completed before its removal.

To complete the servlet’s service () method server calls the destroy () method only after all the requests are responded or after a specified grace period provided by the server which will be come first.  The destroy () is called first  and it  will be called by the servlet-container at the time the servlet will be shut-down. The finalize () is called by the JVM (Java Virtual Machine) before the garbage-collector claims the objects (and isn’t assured to be called at all).

For Example: – Consider we are initializing the object bookDB by using the init () method. The code for destroying that object is given below

public void destroy() {
bookDB = null;
}

A servlet is removed, when all of the service () method should be completed. The server check this completion process by calling the destroy () method only after all service requests have returned or after a specific time period, whichever comes first.

If the servlet takes long running service request, we are using some techniques. There are mainly three types of technique we used

1)      Know how many threads are currently running the service () method.

2)      Notifying methods to shut down

3)      Creating polite long running methods

1) Know how many threads are currently running the service() method

In this method we are tracking or counting the number of service method that is running. In our servlet class we are using a field that helps to count the number of currently running process. This field should have synchronized access methods and this field is increment, decrement, and return the value.

Eg:-

public class ShutdownExample extends HttpServlet {
private int serviceCounter = 0;
...
//Access methods for serviceCounter
protected synchronized void enteringServiceMethod() {
serviceCounter++;
}
protected synchronized void leavingServiceMethod() {
serviceCounter--;
}
protected synchronized int numServices() {
return serviceCounter;}}

The service method should increment the service counter each time the method is entered and should decrement the counter each time the method returns. This is one of the few times that your HttpServlet subclass should override the service method. The new method should call super.service to preserve all of the original service method’s functionality:

protected void service(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException {
enteringServiceMethod();
try {
super.service(req, resp);
} finally {
leavingServiceMethod();
}
}

2) Notifying methods to shut down

It provide a clean shutdown by having the destroy method notify long-running threads of the shutdown and wait for them to complete. To assure a clean shutdown, the destroy () method should not release any shared resources until all of the service requests have completed. There are two parts to doing this process

1)      To check the service counter

2)      To notify the long-running methods that it is time to shut down. For this process, another field is required. The field must be the usual access methods.

public class ShutdownExample extends HttpServlet {
private boolean shuttingDown;
...
//Access methods for shuttingDown
protected synchronized void setShuttingDown(boolean flag) {
shuttingDown = flag;
}
protected synchronized boolean isShuttingDown() {
return shuttingDown;
}
}

An example of the destroy method using these fields to provide a clean shutdown follows:

public void destroy() {
/* Check to see whether there are still service methods /*
/* running, and if there are, tell them to stop. */
if (numServices() > 0) {
setShuttingDown(true);
}
/* Wait for the service methods to stop. */
while(numServices() > 0) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
}
}
}

3) Creating   polite long running methods

Have the long-running methods poll periodically to check for shutdown and, if necessary, stop working, clean up, and return. The final step in providing a clean shutdown is to make any long-running methods behave politely. Methods that might run for a long time should check the value of the field that notifies them of shutdowns and should interrupt their work, if necessary.

public void doPost(...) {
...
for(i = 0; ((i < lotsOfStuffToDo) &&
!isShuttingDown()); i++) {
try {
partOfLongRunningOperation(i);
} catch (InterruptedException e) {
...
}
}
}

Eg: – Sample source code to write Hello World

 

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException
{
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy()
{
// do nothing.
}
}
Finalizing a Servlet


In the above  figure, first the HTTP requests coming to the server are delegated to the servlet container. Then the servlet container loads the servlet before invoking the service() method. After that the servlet container handles multiple requests by spawning multiple threads, each thread executing the service () method of a single instance of the servlet.