4

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?

knorv
  • 49,059
  • 74
  • 210
  • 294
  • Might want to look into this too: http://stackoverflow.com/questions/184147/countdownlatch-vs-semaphore – Daniel Ryan Oct 03 '11 at 22:13
  • for those who have similar problem, but with async call see https://stackoverflow.com/a/69234939/1220560 – morgwai Sep 19 '21 at 02:51

2 Answers2

13

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.

steffen
  • 16,138
  • 4
  • 42
  • 81
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
-1

CountDownLatch

May solve your problem.

It comes in blocking and non blocking.

Edit: Fix URL

user85155
  • 1,370
  • 16
  • 24
  • 2
    no, the latch is used for entirely different tasks (like waiting N tasks to complete). the answer is misleading and mostly incorrect. You are looking for Semaphore. – bestsss Oct 27 '11 at 10:50