Java Concurrency Interview

synchronized, monitors, wait and notify question 30 of 180 junior

Why does wait() throw IllegalMonitorStateException sometimes?

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.

wait-notify

Quiz yourself on synchronized, monitors, wait and notify Suggest a correction