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

Ernie picture Ernie · Aug 24, 2012 · Viewed 10.6k times · Source

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

Answer

nos picture nos · Aug 24, 2012

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