synchronized, monitors, wait and notify question 30 of 180 junior
Why does wait() throw IllegalMonitorStateException sometimes?
- Because the object is null
- Correct: Because
wait,notifyandnotifyAllmay only be called by a thread that owns that object's monitor - Because
wait()was called on a different thread - Because the timeout was negative
wait() releases the monitor, so it must hold it first. Calling obj.wait() outside
synchronized (obj) throws immediately, and so does calling obj.wait() inside
synchronized (otherObj). The exception is one of the friendlier parts of the API: the alternative
would be a silent race.
Remember that wait releases only the monitor it was called on. A thread holding two monitors and
waiting on one keeps the other, which is a fine way to build a deadlock.
Quiz yourself on synchronized, monitors, wait and notify Suggest a correction