![](/img/trans.png)
[英]Java ReentrantLock.unlock/await()/signal() not throwing IllegalMonitorStateException
[英]Unlock on ReentrantLock without IllegalMonitorStateException
我有一段代碼(簡化):
if(reentrantLockObject.isLocked()) {
reentrantLockObject.unlock();
}
其中 reentrantLockObject 是 java.util.concurrent.locks.ReentrantLock。 有時我會收到 IllegalMonitorStateException。 它接縫在 check 和 unlock() 調用之間釋放了鎖。 我怎樣才能防止這個例外?
isLocked
返回任何線程是否持有鎖。 我想你想要isHeldByCurrentThread
:
if (reentrantLockObject.isHeldByCurrentThread()) {
reentrantLockObject.unlock();
}
話雖如此, isHeldByCurrentThread
被記錄為主要用於診斷目的 - 這段代碼是正確的方法是不尋常的。 你能解釋為什么你認為你需要它嗎?
你需要擁有鎖才能解鎖它。 reentrantLockObject.isLocked()僅在某些線程擁有鎖時才為true,不一定是你。
reentrantLockObject.lock();
try{
// do stuff
}finally{
reentrantLockObject.unlock();
}
這里線程擁有鎖,因此他們可以解鎖它。
ReentrantLock
根據以下邏輯拋出此異常:
if (Thread.currentThread() != getExclusiveOwnerThread()) {
throw new IllegalMonitorStateException();
}
所以解決方案是檢查同一個線程是否正在解鎖:
if (reentrantLockObject.isHeldByCurrentThread()) {
reentrantLockObject.unlock();
}
private ReentrantLock lock = new ReentrantLock();
if (lock.tryLock()) {
try {
//your code
} finally {
lock.unlock();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.