Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 (10).

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?

like image 287
knorv Avatar asked Dec 16 '22 08:12

knorv


1 Answers

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.

like image 180
JB Nizet Avatar answered Jan 12 '23 01:01

JB Nizet