在处理一个项目时,我遇到了这段用于生产系统的代码:
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/