IllegalMonitorStateException
Learn the reasons that cause IllegalMonitorStateException to be thrown.
We'll cover the following
If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.
Explanation
The IllegalMonitorStateException
is a common programming error that can show up in concurrent programs. Depending on the structure of the program, the exception may occur consistently or only occasionally. The IllegalMonitorStateException
exception class extends the RuntimeException
class and according to the official documentation is thrown to indicate that a thread has attempted to wait on an object’s monitor or to notify other threads waiting on an object’s monitor without owning the specified monitor. In other words if you invoke wait()
or notify()
/notifyAll()
without synchronizing on the object i.e. outside of a synchronized
method or block (with the object as the synchronization target) then IllegalMonitorStateException
will be thrown. Similarly, the exception is thrown when you invoke these methods on an instance of Condition
class without acquiring the associated lock with the condition. The class is part of the java.lang
package and not java.util.concurrent.*
.
Repro using Lock
The program below demonstrates generating IllegalMonitorStateException
using a Condition
object that was instantiated from a Lock
object.
Create a free account to view this lesson.
Continue your learning journey with a 14-day free trial.
By signing up, you agree to Educative's Terms of Service and Privacy Policy