Reputation: 55
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?
Upvotes: 1
Views: 270
Reputation: 51587
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.
Upvotes: 4