华盛顿大学进行了Study of Common Pitfalls in Simple Multi-Threaded Programs。检测到的错误分为3类:数据竞争,死锁和杂项 在杂项类别中有一个我不明白的错误:
不必要地使用中断禁用和锁定获取和释放
中断禁用和锁定获取和释放意味着什么?
为什么不能一起使用?
有人可以解释一下吗?
答案 0 :(得分:1)
不必要地使用中断禁用
public void run(){
while(true){
//some deep logic
try{
Thread.sleep(5000);
}catch(InterruptedException){
//eating away the exception without taking any steps
}
}
}
所以现在运行这个逻辑的线程不能被中断,因为它正在消耗异常所以它被称为中断禁用,唯一的方法就是杀死这个非常糟糕的程序它可以使数据结构处于不正确的状态。
不必要地使用锁定获取和释放
class Test{
private int counter = 0;
public synchronized void increment(){ counter++; }
public synchronized void decrement(){ counter--;}
//Unnecessary placement of synchronized block here
public synchronized void printString(){
//this method does not use counter so no need to use synchronized block
}
}