IllegalMonitorStateException on wait() call
You need to be in a synchronized
block in order for Object.wait()
to work.
Also, I recommend looking at the concurrency packages instead of the old school threading packages. They are safer and way easier to work with.
Happy coding.
EDIT
I assumed you meant Object.wait()
as your exception is what happens when you try to gain access without holding the objects lock.
wait
is defined in Object
, and not it Thread
. The monitor on Thread
is a little unpredictable.
Although all Java objects have monitors, it is generally better to have a dedicated lock:
private final Object lock = new Object();
You can get slightly easier to read diagnostics, at a small memory cost (about 2K per process) by using a named class:
private static final class Lock { }private final Object lock = new Lock();
In order to wait
or notify
/notifyAll
an object, you need to be holding the lock with the synchronized
statement. Also, you will need a while
loop to check for the wakeup condition (find a good text on threading to explain why).
synchronized (lock) { while (!isWakeupNeeded()) { lock.wait(); }}
To notify:
synchronized (lock) { makeWakeupNeeded(); lock.notifyAll();}
It is well worth getting to understand both Java language and java.util.concurrent.locks
locks (and java.util.concurrent.atomic
) when getting into multithreading. But use java.util.concurrent
data structures whenever you can.
I know this thread is almost 2 years old but still need to close this since I also came to this Q/A session with same issue...
Please read this definition of illegalMonitorException again and again...
IllegalMonitorException 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.
This line again and again says, IllegalMonitorException comes when one of the 2 situation occurs....
1> wait on an object's monitor without owning the specified monitor.
2> notify other threads waiting on an object's monitor without owning the specified monitor.
Some might have got their answers... who all doesn't, then please check 2 statements....
synchronized (object)
object.wait()
If both object are same... then no illegalMonitorException can come.
Now again read the IllegalMonitorException definition and you wont forget it again...