From the Java java.util.concurrent.Semaphore docs it wasn't quite clear to me what happens if semaphore.acquire() blocks the thread and later gets interrupted by an InterruptedException. Has the semaphore value been decreased and so is there a need to release the semaphore?
Currently I am using code like this:
try {
// use semaphore to limit number of parallel threads
semaphore.acquire();
doMyWork();
}
finally {
semaphore.release();
}
Or should I rather not call release() when an InterruptedException occurs during acquire() ?
Yes, a negative value means you have processes waiting for the semaphore to be released. A positive value means you can call acquire that many times before the semaphore blocks.
Exits the semaphore a specified number of times and returns the previous count.
There is no requirement that a thread that releases a permit must have acquired that permit by calling acquire().
A semaphore can be released by any thread. A thread can call a wait function repeatedly on a mutex without blocking. However, if you call a wait function twice on a binary semaphore without releasing the semaphore in between, the thread will block.
nos's accepted answer is partially correct, except semaphore.acquire() also throws InterruptedException. So, to be 100% correct, the code would look like:
try {
semaphore.acquire();
try {
doMyWork();
} catch (InterruptedException e) {
// do something, if you wish
} finally {
semaphore.release();
}
} catch (InterruptedException e) {
// do something, if you wish
}
call release() when an InterruptedException occurs during acquire() ?
You should not. If .acquire() is interrupted, the semaphore is not acquired, so likely should not release it.
Your code should be
// use semaphore to limit number of parallel threads
semaphore.acquire();
try {
doMyWork();
}
finally {
semaphore.release();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With