Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to limit number of threads running certain section of code in Java?

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.

like image 623
user2196351 Avatar asked Jul 24 '16 12:07

user2196351


People also ask

How will restrict a block of code only for certain number of threads?

Use a semaphore with three permits: Semaphores are often used to restrict the number of threads that can access some (physical or logical) resource.

Is there a limit to the number of threads in Java?

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.

How can we stop a thread in the middle of execution in Java?

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.

How do you manage threads in Java?

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 .


1 Answers

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.

like image 104
Bex Avatar answered Oct 14 '22 12:10

Bex