Interview Q&A · Java · 6 questions in this topic

wait(), notify() and Inter-Thread Communication — Java Interview Q&A

All Java topics

How wait, notify, and notifyAll enable inter-thread communication on a shared monitor. Part of Threads & Concurrency · 294 questions in the Java bank.

How do threads communicate?

Answer

The classic approach is shared state guarded by a lock, combined with wait, notify, and notifyAll for signalling. One thread changes the shared condition inside a synchronized region and notifies, while another thread waits for that condition. Modern Java prefers higher level channels such as BlockingQueue, Future, CompletableFuture, and concurrent collections. These hide the low level signalling and are less error prone.

Explain wait(), notify(), notifyAll().

Answer

Wait tells the current thread to release the monitor it holds and park until it is notified or interrupted. Notify wakes one arbitrary thread waiting on the same object, while notifyAll wakes every thread waiting on it, letting each re-compete for the lock. All three may only be called while holding the object monitor, otherwise they throw IllegalMonitorStateException. Wait also throws InterruptedException, and callers must recheck their condition in a loop because of spurious wakeups.

Example

Example.javajava
synchronized(queue) {
    while (queue.isEmpty()) {
        try {
            queue.wait();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    queue.remove();
    queue.notifyAll();
}

Why are they on Object instead of Thread?

Answer

Wait and notify coordinate around a shared object, not around a single thread. Every Java object has a monitor, so any object can serve as the meeting point where threads wait for a condition and where other threads signal a change. Placing these methods on Thread would wrongly suggest they control a specific thread. The design therefore puts the signalling methods on the thing threads share, which is the Object.

Learn this topic

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits