Hackforge Academy

Category: java

wait, notify, and notifyAll Overview

Published on 27 Oct 2026

Explanation

These Object methods coordinate threads using a monitor. A thread must own that object's monitor to call them. wait() releases the monitor and waits; notify() wakes one waiter; notifyAll() wakes all waiters.

Code:

public class WaitNotifyDemo {
    private static final Object LOCK = new Object();
    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(() -> {
            synchronized (LOCK) {
                try { LOCK.wait(); }
                catch (InterruptedException e) { Thread.currentThread().interrupt(); }
                System.out.println("Worker resumed");
            }
        });
        worker.start();
        Thread.sleep(100);
        synchronized (LOCK) { LOCK.notify(); }
    }
}

Explanation

When a thread calls wait() while holding an object's monitor, it releases that monitor and enters a waiting state. Before returning from wait(), it must reacquire the monitor. Always check the condition in a loop.

Code:

public class WaitConditionDemo {
    private static final Object LOCK = new Object();
    private static boolean ready = false;
    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (LOCK) {
                while (!ready) {
                    try { LOCK.wait(); }
                    catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
                }
                System.out.println("Ready to continue");
            }
        }).start();
    }
}

Explanation

notify() selects one thread waiting on the same object's monitor. The selected thread cannot continue until it reacquires the monitor. If multiple waiters have different conditions, waking an arbitrary waiter may not be appropriate.

Code:

public class NotifyOneDemo {
    private static final Object LOCK = new Object();
    private static boolean ready;
    public static void main(String[] args) {
        Thread worker = new Thread(() -> {
            synchronized (LOCK) {
                while (!ready) {
                    try { LOCK.wait(); }
                    catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
                }
                System.out.println("Condition satisfied");
            }
        });
        worker.start();
        synchronized (LOCK) { ready = true; LOCK.notify(); }
    }
}

Explanation

notifyAll() wakes all threads waiting on that monitor. They compete to reacquire the lock and each must recheck its condition. It is often safer when multiple threads wait on conditions associated with the same monitor.

Code:

public class NotifyAllDemo {
    private static final Object LOCK = new Object();
    private static boolean ready;
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) new Thread(() -> {
            synchronized (LOCK) {
                while (!ready) {
                    try { LOCK.wait(); }
                    catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
                }
                System.out.println(Thread.currentThread().getName() + " resumed");
            }
        }).start();
        synchronized (LOCK) { ready = true; LOCK.notifyAll(); }
    }
}

Explanation

Calling wait(), notify(), or notifyAll() without owning the monitor throws IllegalMonitorStateException. Use while rather than if to handle spurious wake-ups and recheck conditions after waking.

Code:

public class CorrectWaitPattern {
    private final Object lock = new Object();
    private boolean available;
    public void awaitAvailability() throws InterruptedException {
        synchronized (lock) {
            while (!available) lock.wait();
        }
    }
    public void makeAvailable() {
        synchronized (lock) { available = true; lock.notifyAll(); }
    }
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community