如果我不中断任何自己,我必须担心InterruptedExceptions? [英] Do I have to worry about InterruptedExceptions if I don't interrupt anything myself?
问题描述
我在一个爱好项目中使用 java.util.concurrent.Semaphore
。它在我写的连接池类中使用。我可以使用它有点大惊小怪,除了这种方法:
public void acquire(int permits)throws InterruptedException
这将强制我处理 InterruptedException
。现在,我不知道什么中断线程甚至意味着,我从来没有这样做(好吧,不是显式)在我的代码。这是否意味着我可以忽略该异常?如何处理?
是的,您需要担心 InterruptedException
,正如你需要担心必须抛出或处理的任何其他已检查异常。
大多数时候, code> InterruptedException 发出停止请求,最有可能是由于运行您的代码的线程中断。
连接池等待连接的特定情况,我会说这是一个取消问题,您需要中止获取,清理和恢复中断的标志(见下文)。
$例如,如果你使用某种类型的
Runnable
/ 可调用
在 Executor
中运行,那么您需要正确处理InterruptedException: executor.execute(new Runnable(){
public void run(){
while(true){
try {
Thread.sleep(1000);
} catch(InterruptedException e){
continue; // blah
}
pingRemoteServer();
}
}
});
这意味着你的任务从不服从执行器使用的中断机制, / shutdown。
相反,正确的习语是恢复中断的状态,然后停止执行:
executor.execute(new Runnable(){
public void run(){
while(true){
try {
Thread.sleep(1000);
} catch(InterruptedException e){
Thread.currentThread()。interrupt(); //恢复中断状态
break;
}
pingRemoteServer();
}
}
});
实用资源:
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
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?
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.
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).
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();
}
}
});
Useful resources:
这篇关于如果我不中断任何自己,我必须担心InterruptedExceptions?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!