wait and notify

Inter-thread Communication

wait(), notify() and notifyAll() are methods of Object. They must be called while holding that object's lock (inside synchronized), otherwise you get IllegalMonitorStateException.

  • wait(): release the lock and sleep until notified.
  • notify(): wake one waiting thread; notifyAll(): wake all of them.
  • Always call wait() in a while loop that re-checks the condition (spurious wake-ups, other consumers).

Producer–Consumer with a Bounded Buffer

Example

The producer blocks when the buffer is full, the consumer blocks when it is empty. Only the consumer prints, so the order is fixed.

import java.util.*;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        BoundedBuffer buffer = new BoundedBuffer(2);
        Thread producer = new Thread(() -> {
            try { for (int i = 1; i <= 6; i++) buffer.put("order-" + i); buffer.put("STOP"); }
            catch (InterruptedException ignored) { }
        });
        Thread consumer = new Thread(() -> {
            try {
                String item;
                while (!(item = buffer.take()).equals("STOP")) System.out.println("Packed " + item);
            } catch (InterruptedException ignored) { }
        });
        producer.start(); consumer.start();
        producer.join(); consumer.join();
        System.out.println("All orders packed");
    }
}

class BoundedBuffer {
    private final Deque<String> items = new ArrayDeque<>();
    private final int capacity;
    BoundedBuffer(int capacity) { this.capacity = capacity; }

    synchronized void put(String item) throws InterruptedException {
        while (items.size() == capacity) wait();
        items.addLast(item);
        notifyAll();
    }

    synchronized String take() throws InterruptedException {
        while (items.isEmpty()) wait();
        String item = items.removeFirst();
        notifyAll();
        return item;
    }
}

Output

Packed order-1
Packed order-2
Packed order-3
Packed order-4
Packed order-5
Packed order-6
All orders packed

Prefer High-level Tools

Note: In real code use BlockingQueue (ArrayBlockingQueue, LinkedBlockingQueue) instead of hand-written wait/notify. put and take already block correctly. Knowing wait/notify is still important for interviews.