Need to semaphore.relase() if semaphore.acquire() gets InterruptedException?

interrupted-exception, java, semaphore

Solution

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();
}

Problem

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() ?

Original source