The .notify() method has to be called from within a synchronized context, ie from inside a synchronized block.
The java.lang.IllegalMonitorStateException is thrown when you call .notify() on an object that is not used as the lock for the synchronized block in which you call notify. For example, the following works;
synchronized(obj){
obj.notify();
}
But this will throw the exception;
synchronized(obj){
// notify() is being called here when the thread and
// synchronized block does not own the lock on the object.
anotherObj.notify();
}
Reference;
- IllegalMonitorStateException API
- How to use wait & notify