I'm surprised to see the below example in the
J2EE tutorial as a way of keeping track of the number of services being handled. There is no mention that if the webcontainer creates multiple instances of the
servlet this method won't work.
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;
}
}
protected void service(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,IOException {
enteringServiceMethod();
try {
super.service(req, resp);
} finally {
leavingServiceMethod();
}
}
I was expecting an example like this, using the same body for service method:
private synchronized enteringServiceMethod()
{
Integer cnt = getServletContext().getAttribute("activeRequests");
if(cnt==null)
cnt = new Integer(0);
cnt.increment();
getServletContext().setAttribute("activeRequests",cnt);
}
private synchronized leavingServiceMethod()
{
Integer cnt = getServletContext().getAttribute("activeRequests");
cnt.decrement();
getServletContext().setAttribute("activeRequests",cnt);
}
}
Agree?