Showing posts with label shutdown methods. Show all posts
Showing posts with label shutdown methods. 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

Notifying Methods to Shut Down in Servlets

See Tracking Service Request
To ensure a clean shutdown, your destroy method should not release any shared resources until all of the service requests have completed. One part of doing this is to check the service counter. Another part is to notify the long-running methods that it is time to shut down. For this notification, another field is required. The field should have 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) {
      }
   }
}