Why am I getting IllegalMonitorStateException?

后端 未结 2 462
借酒劲吻你
借酒劲吻你 2021-01-19 01:14

I get the following Exception being thrown when I try to unlock an object.

Exception in thread \"Thread-1\" java.lang.IllegalMonitorStateException
    at jav         


        
2条回答
  •  旧巷少年郎
    2021-01-19 02:00

    I know this question is more than a year old, but I was facing the same problem and the solution turned out to be not another Thread that was holding the Lock somehow but basically a very simple mistake and the inner details of a ReentrantLock. If we look at the implementation of tryRelease:

    protected final boolean tryRelease(int releases) {
      int c = getState() - releases;
      if (Thread.currentThread() != getExclusiveOwnerThread())
         throw new IllegalMonitorStateException();
      ..
      if (c == 0) {
        ..
        setExclusiveOwnerThread(null);
      }
      ..
    }
    

    If the release-count drops to zero, the exclusiveOwnerThread is set to null. And if you afterwards try to release the lock once more, you're not the exclusiveOwnerThread anymore, since your Thread is unlikely to be null. So one simple .unlock() too much can lead to this (in this situation rather confusing) Exception.

提交回复
热议问题