Servlet Finalization

In this tutorial you will learn about what happens when a servlet is going to be finalize.

Servlet Finalization

In this tutorial you will learn about what happens when a servlet is going to be finalize.

Servlet Finalization

Servlet Finalization

In this tutorial you will learn about what happens when a servlet is going to be finalize.

A servlet container can calls the destroy() method of Servlet interface when it found that the servlet should be deleted from the service() method due to the recovery of memory resources or on being shutdown, etc. When a destroy() method is called it releases the any resources that is used by the servlet such as the database object created in the init() method and saves the persistent state. When a 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. In such a case that a servlet created by you has the longer execution time than the server's grace period could still be run on calling of destroy() method.

Before finalizing a servlet, servlet container calls the destroy() method to insure whether any service method is completed or not. It may possible that various of threads are running when the destroy method is called you can find the number of currently running threads by including a field and the respective method for accessing this field in your servlet class. There may be an another case that the method which will run longer is to be notified for shutting down time you are required an another field and the respective method for accessing the field in your servlet class, finally a long running method that is notified for shutting down let check its notifies field value and provide it a clean shutdown if required, then it should be interrupt their work.

For Example :

To find out the currently running thread you can include the counter field and its accessing method in your servlet class as :

/*
{
int counter=0;

protected synchronized void in()
{
counter++;
}
protected synchronized void out()
{
counter--
}
protected synchronized int display()
{
return counter;
}
*/

To notify the long running methods that it's time to shutdown you can include the field value and its respective accessing method in your servlet class as :

/*
{
boolean timeToShutDown;

protected synchronized void setShutDown(boolean flag)
{
timeToShutDown=flag;
}
protected synchronized boolean isShutDown()
{
return timeToShutDown;
}
*/