Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there any flaw in this code?
    primarykey
    data
    text
    <p>I wrote a servlet, but the servlet is not yet in production stage.</p> <p>I've added a counter in the Filter of the servlet, so that when number of concurrent request reach a limit, no more people can be accepted. I worry some marginal case, for example: Say the system has already reached 49 concurrent request(50 is max), and in the synchronized block it makes the boolean variable "ok" to True, then at the next instance, multiple thread see that the servlet is available and rush into that and break the limit.</p> <p>Please help to check this code if there is any flaw:</p> <pre><code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub // place your code here // pass the request along the filter chain conditionalInfoLog(logEnabled, "Incoming request..."); conditionalInfoLog(logEnabled, "Number of concurrent request(s): " + count); boolean ok; synchronized (lock) { ok = count &lt; limit; if(ok){ count++; } } if (ok) { try{ // let the request through and process as usual conditionalInfoLog(logEnabled, "Request accepted and processing, number of concurrent request(s): " + count); chain.doFilter(request, response); }catch(Exception ex){ conditionalErrorLog(logEnabled, ex.getMessage()); String xmlStr = genXmlErrMsg(ex.getMessage()); response.setContentType("text/xml"); response.getWriter().print(xmlStr); }finally{ synchronized (lock) { count--; } conditionalInfoLog(logEnabled, "End of request. Number of concurrent request(s): " + count); } } else { // handle limit case, e.g. return status code 503 conditionalInfoLog(logEnabled, busyMsg); String xmlStr = genXmlErrMsg(busyMsg); response.setContentType("text/xml"); response.getWriter().print(xmlStr); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload