CKTIS / Java
IllegalMonitorStateException — missing monitor ownership
IllegalMonitorStateException indicates, among other cases, a call to wait(), notify(), or notifyAll() without owning the target object's monitor. Fixing it requires synchronization on the correct object, not merely catching the exception.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
public class IllegalMonitorStateException extends RuntimeException
IllegalMonitorStateException()
IllegalMonitorStateException(String s)IllegalMonitorStateException in java.lang directly extends RuntimeException. It is unchecked: neither a throws declaration nor a catch is required. The constructor IllegalMonitorStateException() supplies no detail message, while IllegalMonitorStateException(String s) accepts one.
Calls to wait(), wait(long), wait(long, int), notify(), and notifyAll() require the current thread to own the monitor of the object receiving the call. A typical solution is synchronized (monitor). Synchronizing on a different object is insufficient. A synchronized instance method locks this, while a static one locks the class's Class object.
The example deliberately triggers and catches the exception, then demonstrates a valid call on the same object inside synchronized. Having no waiting threads does not cause the exception. In real code, fix monitor ownership rather than ignoring the error. When using wait(), check the condition in a while loop because spurious wakeups are possible; InterruptedException is a separate concern requiring handling.
Examples
public class Main {
public static void main(String[] args) {
Object monitor = new Object();
try {
monitor.notifyAll();
} catch (IllegalMonitorStateException e) {
System.out.println(e.getClass().getSimpleName());
}
synchronized (monitor) {
monitor.notifyAll();
System.out.println("Monitor owned: OK");
}
}
}Result
IllegalMonitorStateException Monitor owned: OK
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.