2010-05-11 111 views
9

我有一段代碼(簡化):解鎖上的ReentrantLock而不拋出:IllegalMonitorStateException

if(reentrantLockObject.isLocked()) { 
     reentrantLockObject.unlock(); 
} 

其中reentrantLockObject是java.util.concurrent.locks.ReentrantLock中。 有時我得到IllegalMonitorStateException。 它在check和unlock()調用之間釋放鎖。 如何防止此異常?

+0

@Mihail,如果你不知道要不要不是你的線程持有鎖,我建議你可能做錯了什麼。 – 2010-05-11 16:33:07

回答

15

isLocked返回是否任意線程持有鎖。我想你想要isHeldByCurrentThread

if (reentrantLockObject.isHeldByCurrentThread()) { 
    reentrantLockObject.unlock(); 
} 

話雖如此,isHeldByCurrentThread被證明是主要用於診斷目的 - 它會爲這段代碼是正確的做法是不尋常的。你能解釋爲什麼你認爲你需要它嗎?

+0

但你可能不想。 – 2010-05-11 14:20:39

+0

@Tom:真的 - 這通常不是一個好主意。將編輯。 – 2010-05-11 14:21:20

6

您需要擁有鎖才能解鎖。只有當某個線程擁有鎖時,reentrantLockObject.isLocked()才爲真,不一定是你。

reentrantLockObject.lock(); 
    try{ 

     // do stuff 
    }finally{ 
     reentrantLockObject.unlock(); 
    } 

這裏線程擁有鎖,所以他們能夠解鎖它。

if (Thread.currentThread() != getExclusiveOwnerThread()) { 
    throw new IllegalMonitorStateException(); 
} 

所以解決的辦法是檢查是否在同一個線程是解鎖:

3

ReentrantLock按照這個邏輯引發此異常

if (reentrantLockObject.isHeldByCurrentThread()) { 
    reentrantLockObject.unlock(); 
} 
相關問題