在 ReentrantLock 上解锁,没有非法MonitorStateException

2022-09-04 05:48:25

我有一段代码(简化):

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

其中 reentrantLockObject 是 java.util.concurrent.locks.ReentrantLock。有时我得到非法的MonitorStateException。它接缝锁是在检查和解锁()调用之间释放的。如何防止此异常?


答案 1

isLocked返回是否有任何线程持有锁。我想你想要:isHeldByCurrentThread

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

话虽如此,记录主要用于诊断目的 - 这段代码是正确的方法将是不寻常的。你能解释一下为什么你认为你需要它吗?isHeldByCurrentThread


答案 2

您需要拥有锁才能解锁它。reentrantLockObject.isLocked() 仅当某个线程拥有锁时才为真,而不一定是你。

  reentrantLockObject.lock();
  try{

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

在这里,线程拥有锁,因此他们能够解锁它。


推荐