忽略已检查的异常永远不会被认为是安全的。
It may seem目前适合您,但如果任何其他程序员使用您的代码/API,他们should期望标准行为:
-
也就是说,线程对中断调用“做出反应”,but线程文档描述的任何“反应”。
-
我的意思是,由线程的开发人员决定并准确记录线程如何处理中断,Java 已经not任何预定义的规则,但您should记录你的线程的“反应”(带有文档注释)。
-
例如,InterruptedException
仅从阻塞方法中抛出(例如Thread.sleep(...)
), but never来自正常的代码行(意味着默认情况下会忽略中断),这允许开发人员选择(并记录)线程的反应,例如:
如果尚未得到支持,则需要时间进行开发。
- Maybe postpone(或软忽略),通过调用
Thread.currentThread().interrupt()
在 catch 块中。
它模拟正常代码运行时发生的中断。
- Maybe crash,通过抛出一个
java.lang.Error
(或子类),并通过InterruptedException
-实例为cause
.
除非有记录,否则这是最不希望或最不期望的。
解释postpone;空的 catch 块是危险的InterruptedException
,由于 JVM 删除了中断标志,因此肯定应该在 catch 块中再次设置它,例如:
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
在我看来,这是最低限度的实现InterruptedException
s。检查是否有isInterrupted
循环中的标志也不会造成太大伤害。
与您未来的程序员自己在项目可能有所增长时需要一两天寻找意外线程行为的麻烦相比,这只是很小的开销。
如果您觉得代码的可读性因这些 catch 实现而受到影响,您可以实现自己的safeSleep
实用方法,它负责Exception
s 并正确设置标志。
On the other hand, InterruptedException
is not thrown by the JVM itself in case of a hardware failure, it is a user indicated Exception
only. So, if you do not propagate your Thread
s reference, there won't be any other Thread
s that are able to call Thread.interrupt()
on it. That's it technically. But you shouldn't underestimate the human factor and your programs evolution.
Edit: As ruakh pointed out, there actually is a way to get a Thread
s reference and thus to schedule an Thread.interrupt()
call. That way the developer in heat may not even have to look at the class, that implements your uninterruptible Thread
. In my opinion that's even another reason, to implement proper exception handling.
Another thing: If you're not throwing an Exception
, logging such an event on a level beyond INFO
may be a good choice.