我不必担心InterruptedExceptions,如果我不中断任何我自己? [英] Do I have to worry about InterruptedExceptions if I don't interrupt anything myself?
问题描述
我在一个爱好项目中使用 java.util.concurrent.Semaphore
。它用于我正在写的连接池类。除了这种方法,我可以使用它:
I'm using java.util.concurrent.Semaphore
in a hobby project. It's used in a connection pool class I'm writing. I can use it with little fuss, except for this method:
public void acquire(int permits) throws InterruptedException
这迫使我处理 InterruptedException
。现在,我不知道什么中断一个线程甚至意味着,我从来没有这样做(好的,没有明确地)在我的代码。这是否意味着我可以忽略这个例外?我应该如何处理?
which forces me to handle the InterruptedException
. Now, I'm not sure what "interrupting" a Thread even means and I'm never doing it (well, not explicitly anyway) in my code. Does this mean I can ignore the exception? How should I handle it?
推荐答案
是的,你需要担心 InterruptedException
,正如你需要担心的任何其他被检查的异常你必须抛出或处理。
Yes, you need to worry about InterruptedException
, just as you need to worry for any other checked exception which you must either throw or handle.
大多数时候,一个 InterruptedException
表示停止请求,很有可能是由于运行代码的线程是中断。
Most of the times an InterruptedException
signals a stop request, most likely due to the fact that the thread which was running your code was interrupted.
连接池等待连接的情况,我会说这是一个取消问题,您需要中止采集,清理和恢复中断的标志(见下文)。
In your particular situation of a connection pool awaiting to aquire a connection, I would say that this is a cancellation issue and you need to abort the aquisition, cleanup, and restore the interrupted flag (see below).
举个例子,如果你使用某种 Runnable
/ Callable
在$ code> Executor 中运行,那么你需要处理InterruptedException prope rly:
As an example, if you're using some sort of Runnable
/Callable
running inside an Executor
then you need to handle the InterruptedException properly:
executor.execute(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch ( InterruptedException e) {
continue; //blah
}
pingRemoteServer();
}
}
});
这意味着你的任务永远不会遵守执行者使用的中断机制,不允许正确取消/关闭。
This would mean that your task never obeys the interruption mechanism used by the executor and does not allow proper cancellation/shutdown.
相反,正确的习语是恢复中断状态,然后停止执行:
Instead, the proper idiom is to restore the interrupted status and then stop execution:
executor.execute(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch ( InterruptedException e) {
Thread.currentThread().interrupt(); // restore interrupted status
break;
}
pingRemoteServer();
}
}
});
有用资源
- Shutting down threads cleanly (Java Specialists)
- Dealing with InterruptedException (Brian Goetz)
这篇关于我不必担心InterruptedExceptions,如果我不中断任何我自己?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!