如果我自己不中断任何事情,我是否必须担心 InterruptedExceptions? [英] Do I have to worry about InterruptedExceptions if I don't interrupt anything myself?

查看:16
本文介绍了如果我自己不中断任何事情,我是否必须担心 InterruptedExceptions?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个业余项目中使用 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/CallableExecutor 中运行,那么你需要处理 InterruptedException正确:

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();
         }
    }
});

<小时>

有用资源:

这篇关于如果我自己不中断任何事情,我是否必须担心 InterruptedExceptions?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆