1. 程式人生 > >Bug:StampedLock的中斷問題導致CPU爆滿

Bug:StampedLock的中斷問題導致CPU爆滿

public class TestStampedLock {
    public static void main(String[] args) throws InterruptedException{
    final StampedLock lock = new StampedLock();
    new Thread(){
       public void run(){
       long readLong = lock.writeLock();
       LockSupport.parkNanos(6100000000L);
       lock.unlockWrite(readLong);
     }
    }.start();
    Thread.sleep(100);
    for( int i = 0; i < 3; ++i)
       new Thread(new OccupiedCPUReadThread(lock)).start();
    }
    private static class OccupiedCPUReadThread implements Runnable{
        private StampedLock lock;
        public OccupiedCPUReadThread(StampedLock lock){
            this.lock = lock;
        }
        public void run(){
            Thread.currentThread().interrupt();
            long lockr = lock.readLock();
            System.out.println(Thread.currentThread().getName() + " get read lock");
            lock.unlockRead(lockr);
        }
    }
}
先開啟一個執行緒獲取寫鎖並保持6秒,再開啟三個帶著中斷狀態的執行緒去獲取讀鎖(readLock方法),結果是3個核心被佔據了近6秒。 原因在於沒有使用儲存/復原中斷狀態的機制,通過hack原始碼,插入儲存中斷和返回前恢復中斷的相關程式碼即可修復:
boolean interrupted = false;
if(interrupted)
    Thread.currentThread().interrupt();
return ns;
if(Thread.interrupted()){
    if(interruptible)
        return cancelWaiter(node, p, true);
    else
        interrupted = true;
}