Jeżeli serwlet ma długo trwające metody, to powinno się go zaprogramować wg schematu z J2EE Tutorial:
  1. Zliczanie wywołań metody service:
    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;	
       }	
    }
    
  2. Zmodyfikowana metoda service. service to rozdzielacz, który wywołuje doGet, doPost, doPut
    protected void service(HttpServletRequest req,	
                   HttpServletResponse resp)	
                   throws ServletException,IOException {	
       enteringServiceMethod();	
       try {	
          super.service(req, resp);	
       } finally {	
          leavingServiceMethod();	
       }	
    }
    
  3. Metody do powiadamiania o zamykaniu:
    public ShutdownExample extends HttpServlet {	
       private boolean shuttingDown;	
       ...	
       //Access methods for shuttingDown	
       protected setShuttingDown(boolean flag) {	
          shuttingDown = flag;	
       }	
       protected boolean isShuttingDown() {	
          return shuttingDown;	
       }	
    }
    
  4. Zmodyfikowany destroy:
    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) {	
          }	
       }	
    } 
    
  5. Zmodyfikowana (grzeczna) metoda doPost:
    public void doPost(...) {	
       ...	
       for(i = 0; ((i < lotsOfStuffToDo) &&
          !isShuttingDown()); i++) {	
          try {	
             partOfLongRunningOperation(i);	
          } catch (InterruptedException e) {	
             ...	
          }	
       }	
    }
    


© 2001-2002 Karol Bieńkowski
http://karolb.prv.pl