繁体   English   中英

在没有 IllegalMonitorStateException 的情况下解锁 ReentrantLock

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM