Why this matters
wait/notifyhas four separate requirements, and omitting any one produces a hang or a missed signal that appears only under load.- The producer-consumer problem is a standard interview exercise, and the blocking-queue answer is both shorter and better.
- Deadlock, livelock and starvation are distinct failures with distinct fixes, and the names are used interchangeably far too often.
wait and notify
These three methods live on Object, because every object has a monitor.
Consumer: queue empty
Producer acquires the lock, adds an item
Consumer wakes, re-checks in a while loop
Consumer takes the item
Loading compiler…
The four requirements
- Call them while holding the monitor. Outside a
synchronizedblock you getIllegalMonitorStateException. - Wait in a
whileloop, never anif. A thread can wake without being notified — a spurious wakeup — and even a genuine notification does not guarantee the condition still holds by the time it reacquires the lock. Re-check always. - Prefer
notifyAll()overnotify().notify()wakes one arbitrary waiter, which may be waiting for a different condition. The right thread then never wakes and the system stalls. wait()releases the monitor;sleep()does not. This is the whole reasonwaitexists.
BlockingQueue does this for you
The whole class above is one line of the standard library.
Loading compiler…
Loading compiler…
No wait, no notify, no synchronized, and no opportunity to get the loop condition wrong.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 4 sections
- Condition objects
- The coordination utilities
- Deadlock, livelock, starvation
- Common misreadings
Test yourself
Answer these before moving on — recall is what makes it stick.