Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 919
Ernie Avatar asked Aug 24 '12 07:08

Ernie


People also ask

Can release be called on a semaphore before 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.

What does semaphore release do?

Exits the semaphore a specified number of times and returns the previous count.

Can thread release permits on a semaphore without having them?

There is no requirement that a thread that releases a permit must have acquired that permit by calling acquire().

Can a semaphore be released by any thread?

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.


2 Answers

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
}
like image 102
jblack Avatar answered Sep 21 '22 13:09

jblack


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();
}
like image 27
nos Avatar answered Sep 24 '22 13:09

nos