Why am I getting IllegalMonitorStateException?

后端 未结 2 459
借酒劲吻你
借酒劲吻你 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 01:45

    The documentation is pretty clear:

    If the current thread is the holder of this lock then the hold count is decremented. If the hold count is now zero then the lock is released. If the current thread is not the holder of this lock then IllegalMonitorStateException is thrown.

    So the thread which is trying to unlock isn't the holder of the lock. We can't tell why you expected it to be the same thread without seeing more of your code.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题