• Post Reply Bookmark Topic Watch Topic
  • New Topic

Is this way of tracking service requests as explained in Sun's J2EE tutorial correct?

 
A Bhattacharya
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35744
412
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Linking to the tutorial page for anyone who wants the context.

I think Sun is just trying to demonstrate the count for an individual servlet. Immediately after this example, they use the counter to see if any service methods are running (in this servlet) for whether it is time to have the destroy method run for a "clean shutdown." In this particular case, it is enough to know whether anyone is executing THIS servlet instance. If someone is still in another instance of servlet, it will not run the destroy logic until that servlet instance is done.

The servletContext example doesn't achieve that purpose. Also note that it won't work if you have multiple clones.
 
A Bhattacharya
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with your answer. Thanks.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!