| Author |
Is this way of tracking service requests as explained in Sun's J2EE tutorial correct?
|
A Bhattacharya
Ranch Hand
Joined: Oct 22, 2007
Posts: 125
|
|
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
internet detective
Marshal
Joined: May 26, 2003
Posts: 26192
|
|
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.
|
[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
|
 |
A Bhattacharya
Ranch Hand
Joined: Oct 22, 2007
Posts: 125
|
|
|
I agree with your answer. Thanks.
|
 |
 |
|
|
subject: Is this way of tracking service requests as explained in Sun's J2EE tutorial correct?
|
|
|