background image

Tracking Service Requests

<< Finalizing a Servlet | Creating Polite Long-Running Methods >>
<< Finalizing a Servlet | Creating Polite Long-Running Methods >>

Tracking Service Requests

Tracking Service Requests
To track service requests, include in your servlet class a field that counts the number of service
methods that are running. The field should have synchronized access methods to increment,
decrement, and return its value.
public class 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;
}
}
The service method should increment the service counter each time the method is entered and
should decrement the counter each time the method returns. This is one of the few times that
your HttpServlet subclass should override the service method. The new method should call
super.service
to preserve the functionality of the original service method:
protected void service(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,IOException {
enteringServiceMethod();
try {
super.service(req, resp);
} finally {
leavingServiceMethod();
}
}
Notifying Methods to Shut Down
To ensure a clean shutdown, your destroy method should not release any shared resources
until all 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;
Finalizing a Servlet
Chapter 4 · Java Servlet Technology
129