CodeBlanks Logo Icon CodeBlanks

wait and notify

Learn thread communication with wait and notify.

wait and notify

wait() and notify() are methods on Object; they let threads that wait on and wake up on a lock communicate. Both must be called from inside a synchronized block.

synchronized (lock) {
    while (!ready) lock.wait();
}
synchronized (lock) {
    ready = true;
    lock.notify();
}

This is the basis of patterns like producer-consumer. wait releases the lock and waits; notify wakes one waiting thread. notifyAll wakes all waiters. This is Java's counterpart of condition variables.

The producer-consumer pattern

A producer adds data to a queue and calls notify; a consumer waits with wait when the queue is empty. This is the classic producer-consumer pattern.

synchronized (queue) {
    while (queue.isEmpty()) queue.wait();
    item = queue.remove(0);
}

The condition is checked with while; if is not enough because another thread can slip in between wake-up and condition check. This prevents spurious wakeup races. Java's BlockingQueue provides this pattern ready-made.

Practice Apply wait/notify with a Signal

Define a Signal class with a boolean sent = false field. A synchronized void send() method sets sent = true and calls notify(). A synchronized void await() method has a while (!sent) wait() loop (wrap InterruptedException in try/catch). In a SignalDemo class write main; call send(), call await() and print System.out.println("Done").

Starter code

Main.java
// Define the Signal class (sent field, send and await methods)

// Write main in SignalDemo; call send and await, then print Done

Sample solution

Main.java
class Signal {
    boolean sent = false;
    synchronized void send() {
        sent = true;
        notify();
    }
    synchronized void await() {
        while (!sent) {
            try { wait(); } catch (InterruptedException e) {}
        }
    }
}

class SignalDemo {
    public static void main(String[] args) {
        Signal s = new Signal();
        s.send();
        s.await();
        System.out.println("Done");
    }
}

Expected output

Done

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the wait call

Question
synchronized (lock) {
    while (!ready) lock.____();
}
Answer
synchronized (lock) {
    while (!ready) lock.wait();
}

Explanation: wait() releases the lock and waits.

2 What happens to the lock when wait() is called?

  • The lock is held, the thread waits
  • The lock is destroyed
  • The lock is released and the thread waits Correct answer
  • The lock is duplicated

Explanation: wait() releases the lock and waits until notified.

3 Match wait/notify concepts

Term Meaning
wait() Releases the lock and waits
notify() Wakes one waiter
notifyAll() Wakes all waiters
synchronized Acquires the lock

All lessons in Advanced