Home » Java » multithreading – How can I make a Java thread do a different task rather than block if a semaphore lock acquire/tryAcquire fails?-Exceptionshub

multithreading – How can I make a Java thread do a different task rather than block if a semaphore lock acquire/tryAcquire fails?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’ve been learning concurrency in java and was looking at java semaphores and ran into a problem. I have multiple threads trying to acquire one of multiple locks to access a critical section protected by a semaphore and want my all threads who have failed to acquire the lock to do a specific task and then attempt to reacquire the lock. Every time the acquisition fails I want the thread to do the waiting task I have made and when it’s done try again. repeat until acquired. Looking at the java docs for the java semaphore class, all the acquire methods seem to do some form of blocking one way or another. How can I accomplish what I want?

How to&Answers:

Use tryAcquire:

while(!done) {
  if(sem.tryAcquire()) {
     // semaphore acquired
     done=true
  } else {
   // Semaphore not acquired, do something else
  }
}

There is another variant of tryAcquire with a timeout and you can use that if you want to wait a while and then continue.