Showing posts with label finalizing servlet. Show all posts
Showing posts with label finalizing servlet. Show all posts

Thursday, 15 December 2011

Creating Polite Long-Running Methods


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) {
         ...
      }
   }
}
See Notifying Methods to Shut Down

Finalizing a Servlet


When a servlet container determines that a servlet should be removed from service (for example, when a container wants to reclaim memory resources, or when it is being shut down), it calls thedestroy method of the Servlet interface. In this method, you release any resources the servlet is using and save any persistent state. The following destroy method releases the database object created in the init method described in Initializing a Servlet:
public void destroy() {
   bookDB = null;
}
 
All of a servlet's service methods should be complete when a servlet is removed. The server tries to ensure this completion by calling the destroy method only after all service requests have returned or after a server-specific grace period, whichever comes first.
If your servlet has potentially long-running service requests, use the techniques described below to do the following:
  • Keep track of how many threads are currently running the service method.
  • Provide a clean shutdown by having the destroy method notify long-running threads of the shutdown and wait for them to complete.
  • Have the long-running methods poll periodically to check for shutdown and, if necessary, stop working, clean up, and return.