Skip to main content
PreparationZone Logo
PrepZone

Coordinating Threads

wait and notify done correctly, blocking queues, and the latch, barrier and semaphore trio.

Pass checkpoint below

Read these first

Why this matters

  • wait/notify has 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
wait() releases the lock so the other thread can make progress, which is the whole point. Always re-check the condition in a loop, because a thread can wake without the condition being true.
Java
Loading compiler…

The four requirements

  • Call them while holding the monitor. Outside a synchronized block you get IllegalMonitorStateException.
  • Wait in a while loop, never an if. 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() over notify(). 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 reason wait exists.

BlockingQueue does this for you

The whole class above is one line of the standard library.

Java
Loading compiler…
Java
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.