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

From the Java java.util.concurrent.Semaphore docs, I was not quite clear what would happen if the .acquire () semaphore blocks the thread and then an InterruptedException is thrown. Is the value of the semaphore reduced, and is there a need to free the semaphore?

I am currently using the following code:

try { // use semaphore to limit number of parallel threads semaphore.acquire(); doMyWork(); } finally { semaphore.release(); } 

Or is it better for me not to call release () when an InterruptException occurs during fetch ()?

+8
java semaphore
source share
3 answers

raise release () when an InterruptException occurs while fetching ()?

You should not. If .acquire () is interrupted, the semaphore is not received, so it should not be released.

Your code should be

 // use semaphore to limit number of parallel threads semaphore.acquire(); try { doMyWork(); } finally { semaphore.release(); } 
+8
source share

nos the accepted answer is partially correct, except for the .acquire () semaphore also throws InterruptedException. So, to be 100% correct, the code would look like this:

 try { semaphore.acquire(); try { doMyWork(); } catch (InterruptedException e) { // do something, if you wish } finally { semaphore.release(); } } catch (InterruptedException e) { // do something, if you wish } 
+3
source share

If the thread is interrupted before the method method is called or while waiting for permission, an Exception will be thrown and the permission will not be saved, so there is no need to issue. Only when you are sure that permission has been obtained (after calling the method of the receiving method) you will need to issue permission. This way you better get before the try block starts, something like:

 sem.acquire(); try{ doMyWork(); }finally{ sem.release(); } 
0
source share

All Articles