简体   繁体   中英

When does IllegalMonitorSttateException thrown?

Object.wait(), Object.notify(), Object.notifyAll() methods throw IllegalMonitorStateException. This exception is thrown if the current thread is not the owner of this object's monitor. But, not getting clearity regarding that without getting object's monitor weather current thread will be able to execute wait / notify / notifyAll on any object ? O/w what are chances for illegal monitor's state ?

Thanks scottb for suggestion. Thanks Henno for reply. One more doubt I am getting is regarding becoming owner of object's monitor:

A thread becomes the owner of an object's monitor in one of the following ways: •By executing a synchronized instance method of that object. •By executing the body of a synchronized statement that synchronizes on the object. •For objects of type Class, by executing a synchronized static method of that class.

First two statements are understood. But what is fundamental with objects of type class ?

As you mention, an IllegalMonitorStateException is thrown when the current thread is not the owner of this object's monitor, ie a lock monitor. This means the current thread has to call wait or notify from within a synchronized code block like:

synchronized(object) {
    object.wait();
}

If you only do

object.wait();

an IllegalMonitorStateException is thrown because the current thread hasn't obtained the object's lock by using synchronized.

If you lock on another object without having the lock monitor on the object it is also thrown:

synchronized(object) {
    someOtherObject.wait();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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