javamultithreadingthreadpoolexecutorservicefuturetask

How to restrict the number of threads using a Java service


My requirement is to restrict the number of threads which uses my service at any point in time. Executor service is not helping me here as my problem space is little different. Let me explain with an example.

I have exposed a REST API which does one job. On the fly, my controller invokes one of the services for the job execution. But I have to make sure only 'n' threads access the service. That means threads/API-access will be continuously growing but at some place, I have to keep them in waiting if 'n' threads are already using the service. And the end of the execution I should get the response from the service and returns back to the endpoint and then to the client.

If I use FutureTask and callable, how and where will I write the .get() method? Because my threads will be continuously growing in number and dynamic in nature.

Hope the problem statement is clear, let me know if more clarification required.


Solution

  • If you just want to restrict the max number of threads which can access your service, then you might use Bounded Semaphore and can provide the max number of permits. Here is the sample code (assuming that your service is singleton) :-

    public class SampleService {
        private Semaphore semaphore = new Semaphore(n, true);
    
        public void someMothod() {
            try {
                semaphore.acquire();
    
                // execute the task
    
            } catch (InterruptedException e) {
            } finally {
                semaphore.release();
            }
    
        }
    }
    

    You have to make sure that only one instance of semaphore is created. If you can have multiple instances of your service in the application, then make semaphore static.

    private static Semaphore semaphore = new Semaphore(n, true);