How to set limit to the number of concurrent request in servlet?

后端 未结 5 1649
轻奢々
轻奢々 2020-12-09 23:55

I got this servlet which return a pdf file to the client web browser. We do not want to risk any chance that when the number of request is too much, the server is paralyzed.

5条回答
  •  天涯浪人
    2020-12-10 00:04

    I've thought about using a static counter to keep track of the number of request, but it would raise a problem of race condition.

    If you use a AtomicInteger for the counter, you will not have the problem of race conditions.

    An other way would be using the Java Executor Framework (comes with Java 1.5). There you are able to limit the number of running threads, and block new once until there is a new free thread.

    But I think the counter would work and be the easyest solution.

    Attention: put the counter relese in a finally block!

    //psydo code
    final AtomicInteger counter;
    ...
    while(true) {
      int v = counter.getValue()
      if (v > max) return FAILURE;
      if(counter.compareAndSet(v, v+1)) break;  
    }
    try{
      doStuff();
    } finally{
      counter.decrementAndGet();
    }
    

提交回复
热议问题