java - 在 Java 中总是忽略调用 Thread sleep() 的 InterruptedException 是否安全

标签 java multithreading exception

在处理一个项目时,我遇到了这段用于生产系统的代码:

public static void sleepUntil(long millisecondToWake) {
    while (true) {
        long currentMillisecond = System.currentTimeMillis();
        if (currentMillisecond >= millisecondToWake) {
            break;
        }
        try {
            Thread.sleep(millisecondToWake - currentMillisecond);
        }
        catch (InterruptedException ignoredException) {
            // do nothing
        }
    }
}

我一直坚持永不丢弃异常的基本原则,正如 Joshua Bloch 在 Effective Java 中所揭示的那样,并以我自己丰富的经验支持调试代码,而其他人确实丢弃了异常。迄今为止,我还没有发现这是一个好主意的案例(有时捕获已检查的异常并抛出运行时是合理的,但我在这里不是在谈论这些案例)。

提前感谢您提出任何意见。

最佳答案

这是一篇关于这个特殊异常的好文章:

http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html

但基本上,它不应该被忽略,代码至少应该做的是传播中断:

catch (InterruptedException e) { 
    // Restore the interrupted status
    Thread.currentThread().interrupt();
}

作者不关心他的Thread的 sleep 被打断(这是吞下异常的正当理由);然而,作者在编写代码时不知道或没有考虑过的线程中的其他地方可能需要中断:

whether or not you plan to act on the interrupt request, you still want to reinterrupt the current thread because a single interruption request may have multiple "recipients." The standard thread pool (ThreadPoolExecutor) worker thread implementation is responsive to interruption, so interrupting a task running in a thread pool may have the effect of both canceling the task and notifying the execution thread that the thread pool is shutting down.

关于java - 在 Java 中总是忽略调用 Thread sleep() 的 InterruptedException 是否安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17832139/

相关文章:

java - 应该使用 bool 还是异常?

android - com.google.gson.JsonSyntaxException : java. lang.IllegalStateException:需要一个字符串,但实际上是 BEGIN_OBJECT

java - 可选择对流应用过滤器

java - 选择超过 10 张图像时应用程序崩溃

java - 如何从另一个线程使 View 无效?

c++ - 多线程代码 : vector<bool> iterators incompatible

java - 在Thread算法工作期间重绘JPanel

Python - Selenium 错误的 url 或服务器无法访问

Java - foo.charAt(i) 的返回值如何作为引用?

java - Android Widget 的点击事件