I'm looking for a way to limit number of threads which can run certain section of code in Java using Semaphores or similar.
We were looking into something similar to Google Guava RateLimiter - but instead of limiting number calls per second we need to limit number of threads to run critical section of code.
The reason why need this is that certain library we are using has issues here so we just looking for a quick workaround.
Use a semaphore with three permits: Semaphores are often used to restrict the number of threads that can access some (physical or logical) resource.
Each JVM server can have a maximum of 256 threads to run Java applications. In a CICS region you can have a maximum of 2000 threads. If you have many JVM servers running in the CICS region (for example, more than seven), you cannot set the maximum value for every JVM server.
Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java. This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected.
Every Java program contains at least one thread: the main thread. Additional threads are created through the Thread constructor or by instantiating classes that extend the Thread class. Java threads can create other threads by instantiating a Thread object directly or an object that extends Thread .
This is exactly what java.util.concurrent.Semaphore
was designed to do. You create a Semaphore
like so:
final int MAX_NOF_THREADS = 5;
final Semaphore mySemaphore = new Semaphore(MAX_NOF_THREADS);
then for the critical area you'd do:
try {
mySemaphore.aquire(); // This will hang until there is a vacancy
do_my_critical_stuff();
} finally {
mySemaphore.release();
}
... as simple as that.
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