3

I have a call() method in my code, which based on certain conditions calls specific methods :

call(){
  if(a){
      methodA(); 
  }
  if(b){
      methodB(); 
  }
  if(c){
      methodC(); 
  }
}

In the above scenario, I want to limit concurrent executions for methodC. How can this be achieved?

Ami
  • 33
  • 3
  • 1
    Can you be a bit more specific about what you mean by "limit" ? – Andrey Taptunov Feb 25 '16 at 08:41
  • Suppose multiple threads (eg. 10 threads) are calling call() method and for all threads if(c) returns true, then at a time only specific number of threads (eg. 3) should execute methodC concurrently. Others will execute after these 3 threads have finished their task. Hence, limiting the concurrent executions of methodC to 3 – Ami Feb 25 '16 at 09:08

2 Answers2

0

What you need here is a Semaphore construct (check the bouncer/night club specification in the example).

// Create the semaphore with 3 slots, where 3 are available.
var bouncer = new Semaphore(3, 3);

call(){
  if(a){
      methodA(); 
  }
  if(b){
      methodB(); 
  }
  if(c){
      // Let a thread execute only after acquiring access (a semaphore to be released).
      Bouncer.WaitOne(); 
      methodC(); 
      // This thread is done. Let someone else go for it 
      Bouncer.Release(1); 
  }
}
Tamas Ionut
  • 4,240
  • 5
  • 36
  • 59
0

If you want to limit the number of concurrent executions to at most one at a time, then you should use a Lock. In Java it should look like:

final Lock lock = new ReentrantLock();
call() {
  if(a) {
      methodA(); 
  }
  if(b) {
      methodB(); 
  }
  if(c) {
      lock.lock();
      try {
         methodC(); 
      } finally {
         lock.unlock();
      }
  }
}

If you want to limit the number of concurrent executions to more than one at a time, you can use a Semaphore; here CONCURRENT_CALLS_ALLOWED is an int.

final Semaphore semaphore = new Semaphore(CONCURRENT_CALLS_ALLOWED);
call() {
  if(a) {
      methodA(); 
  }
  if(b) {
      methodB(); 
  }
  if(c) {
      semaphore.aquire();//throws checked exception
      try {
         methodC(); 
      } finally {
         semaphore.release();
      }
  }
}
Random42
  • 8,989
  • 6
  • 55
  • 86