Best way to limit the number of threads executing a particular section of code in Java?

I am looking for a way to limit the number of threads that can run a specific section of code in Java using semaphores or similar.

We studied something similar to the Google Guava RateLimiter - but instead of limiting the number of calls per second, we need to limit the number of threads to run a critical section of code.

The reason this is necessary is because the specific library we use has problems here, so we are just looking for a quick workaround.

+4
source share
2 answers

, java.util.concurrent.Semaphore. Semaphore :

final int MAX_NOF_THREADS = 5;
final Semaphore mySemaphore = new Semaphore(MAX_NOF_THREADS);

:

try {
    mySemaphore.aquire(); // This will hang until there is a vacancy
    do_my_critical_stuff();
} finally {
    mySemaphore.release();
}

... .

+4

, Semaphore - ( @Bex), , ExecutorService. , Callable, -:

// Task that will be executed
public class MyTask implements Callable<Void> {
    @Override
    public Void call() {
        // Do the work here
        return null;
    }
}

// Service to execute tasks in no more than 5 parallel threads
// Cache it after creation and use when you need to execute a task
int maxThreadsCount = 5;
ExecutorService executor = Executors.newFixedThreadPool(maxThreadsCount);

// Execute a task. It will wait if all 5 threads are busy right now.
executor.submit(new MyTask());

ExecutorService Runnable Callable, invokeAll() execute, , , .

Java 8 , lambdas :

executor.submit(() -> {
    // Do the work here
});
+4

Source: https://habr.com/ru/post/1648932/


All Articles