java 如果 semaphore.acquire() 得到 InterruptedException 需要 semaphore.relase() 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12104978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:36:14  来源:igfitidea点击:

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

javasemaphoreinterrupted-exception

提问by Ernie

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?

从 Java java.util.concurrent.Semaphore 文档中,我不太清楚如果 semaphore.acquire() 阻塞线程然后被 InterruptedException 中断会发生什么。信号量值是否降低了,是否需要释放信号量?

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

或者我应该在 Acquire() 期间发生 InterruptedException 时不调用 release() 吗?

回答by nos

call release() when an InterruptedException occurs during acquire() ?

在acquire() 期间发生InterruptedException 时调用release() 吗?

You should not. If .acquire() is interrupted, the semaphore is not acquired, so likely should not release it.

你不应该。如果 .acquire() 被中断,则不会获取信号量,因此可能不应释放它。

Your code should be

你的代码应该是

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

回答by jblack

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

nos 接受的答案是部分正确的,除了 semaphore.acquire() 也会抛出 InterruptedException。因此,要 100% 正确,代码将如下所示:

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

回答by dan

If the thread is interrupted before acquire method call, or while waiting to acquire a permit the InterruptedException will be thrown and no permit will be hold, so no need to release. Only when you are certain that a permit was acquired (after calling the acquire method call) you will need to release the permit. So you better acquire before your try block starts, something like:

如果线程在获取方法调用之前被中断,或者在等待获取许可时,将抛出 InterruptedException 并且不会持有许可,因此无需释放。只有当您确定获得了许可时(在调用 Acquire 方法调用之后),您才需要释放许可。所以你最好在你的 try 块开始之前获取,比如:

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