Java 如果semaphore.acquire()得到InterruptedException,需要使用semaphore.relase()吗?

Java 如果semaphore.acquire()得到InterruptedException,需要使用semaphore.relase()吗?,java,semaphore,interrupted-exception,Java,Semaphore,Interrupted Exception,从Java.util.concurrent.Semaphore文档中,我不太清楚如果Semaphore.acquire()阻塞线程,然后被InterruptedException中断会发生什么。信号量值是否已减小,因此是否需要释放信号量 目前我使用的代码如下: try { // use semaphore to limit number of parallel threads semaphore.acquire(); doMyWork(); } finally { semapho

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

目前我使用的代码如下:

try {
  // use semaphore to limit number of parallel threads
  semaphore.acquire();
  doMyWork();
}
finally {
  semaphore.release();
}
或者在acquire()期间发生InterruptedException时,我不应该调用release()

在acquire()期间发生中断异常时调用release()

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

你的代码应该是

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

如果线程在acquire方法调用之前中断,或者在等待获取许可证时中断,则会抛出InterruptedException,并且不会保留任何许可证,因此无需释放。只有在确定已获取许可证时(调用acquire方法调用后),才需要释放许可证。因此,您最好在试块开始前获取,例如:

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

nos接受的答案部分正确,但信号量除外。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
}

问题是semaphore.acquire()也抛出InterruptedException。是否真的需要嵌套try-catch?我们能在一次try-catch中获取并释放信号量吗?假设您想在调用semaphore.acquire()抛出InterruptedException时优雅地处理这种情况,那么嵌套的try-catch是必要的。InterruptedException可以在调用semaphore.acquire()期间和获取之后抛出。如果我使用泛型的
异常e
而不是
中断异常e
,可以吗?
doMyWork()
没有特别的理由想要抛出
中断异常。如果代码没有等待,只是执行非阻塞任务,则不会抛出中断异常。因此,内部try可能只有finally子句,而没有捕获。