开发者

Limiting to at max N concurrent calls to a static method in Java

开发者 https://www.devze.com 2023-04-10 02:55 出处:网络
Consider the following static method: public void static foo() { // some heavy operation operating on a shared resource.

Consider the following static method:

public void static foo() {
  // some heavy operation operating on a shared resource.
}

Assume that the system becomes unstable when the number of concurrent calls to foo() exceeds ten (开发者_StackOverflow10).

If I in this scenario spin up 100 threads all hammering foo() with requests then the application will become unstable since we exceed the number of concurrent requests which the system can handle.

One way to increase stability to the price of limited concurrency is the change the code to:

public void static synchronized foo() {
  // some heavy operation operating on a shared resource.
}

The system will now be able to handle 100 threads all hammering foo() with requests since only one call at a time will be allowed to foo().

What about the scenario that I want to limit access to foo() so that only N concurrent requests are allowed? What is the simplest way to achieve such a limitation in Java?


Use a Semaphore initialized with 10 permits. Acquire a permit at the beginning of the method, and release it (in a finally block) at the end of the method.


CountDownLatch

May solve your problem.

It comes in blocking and non blocking.

Edit: Fix URL

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号