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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With