Explanation
What just happened
waiter called lock.wait() without holding lock’s monitor. Java checks that before waiting, so it threw IllegalMonitorStateException: current thread is not owner straight away. Nobody caught it, so the waiter thread ended, and main carried on.
Try the what-if switch
- wrong object: waiter is inside
synchronized, but onMain.class, and waits onlock. Same exception. - the fix: both threads lock
lockitself.wait()lets go of it while waiting, so notifier gets in and callsnotifyAll().
Why
wait() must give up a monitor while it sleeps and take it back after, so the thread has to hold that object’s monitor first. notify() needs it too, so a notify can’t slip in between your check and your wait.
How to fix it
Wrap the call in synchronized on the very object you call it on, and check the condition in a while loop:
synchronized (lock) { while (!ready) lock.wait(); }.
Watch out
It’s unchecked, so the compiler never warns you. For new code, a CountDownLatch or a BlockingQueue avoids wait() and notify() altogether.
Common questions
What does current thread is not owner mean?
The thread called wait(), notify() or notifyAll() on an object without holding that object's monitor. Java checks this first and throws IllegalMonitorStateException at once, so the thread never waits.
Why does it still throw inside synchronized?
The block locks a different object. synchronized (Main.class) around lock.wait() holds the monitor of Main.class, not of lock, and only lock's own monitor counts.
Does it crash the whole program?
No, only the thread that threw. The JVM prints Exception in thread "waiter" with the stack trace, that thread ends, and main carries on.
Can ReentrantLock throw it too?
Yes. unlock() from a thread that doesn't hold the lock throws IllegalMonitorStateException as well.
Verified: this timeline matches a real program, checked in CI on JDK 21 and 25. How we verify. Unclear or wrong? Tell us