Search code examples
javamultithreadingconcurrency

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.


Solution

  • 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.acquireUninterruptibly(); // This will hang until there is a vacancy
        do_my_critical_stuff();
    } finally {
        mySemaphore.release();
    }
    

    ... as simple as that.