public 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; } } |
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException { enteringServiceMethod(); try { super.service(req, resp); } finally { leavingServiceMethod(); } } |
public ShutdownExample extends HttpServlet { private boolean shuttingDown; ... //Access methods for shuttingDown protected setShuttingDown(boolean flag) { shuttingDown = flag; } protected boolean isShuttingDown() { return shuttingDown; } } |
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) { } } } |
public void doPost(...) { ... for(i = 0; ((i < lotsOfStuffToDo) && !isShuttingDown()); i++) { try { partOfLongRunningOperation(i); } catch (InterruptedException e) { ... } } } |