Java wait()

Introduction

In Java multithreading, communication between threads is just as important as executing multiple threads simultaneously. Sometimes one thread needs to pause its execution until another thread completes a task or makes a shared resource available. Java provides the wait() method to solve this problem.

The wait() method allows a thread to temporarily release the lock it holds on an object and enter a waiting state. Another thread can then perform the required work and wake up the waiting thread using the notify() or notifyAll() method.

The wait() method is one of the core methods for Inter-Thread Communication in Java. It is defined in the Object class and is commonly used in producer-consumer problems, task coordination, and thread synchronization.

What is Java wait()?

The wait() method causes the current thread to release the monitor (lock) of an object and wait until another thread notifies it.

Unlike Thread.sleep(), the wait() method:

  • Releases the object’s lock.
  • Places the thread into the WAITING state.
  • Requires the thread to own the object’s monitor before calling it.
  • Must be called from inside a synchronized method or synchronized block.

The wait() method belongs to the Object class, which means every Java object inherits it.

Syntax

Java provides three overloaded versions of the wait() method.

1. wait()

public final void wait() throws InterruptedException

The thread waits indefinitely until another thread calls notify() or notifyAll().

2. wait(long timeout)


public final void wait(long timeout)
        throws InterruptedException

The thread waits for the specified number of milliseconds or until it is notified.

3. wait(long timeout, int nanos)


public final void wait(long timeout, int nanos)
        throws InterruptedException

The thread waits for the specified milliseconds and additional nanoseconds or until it is notified.

How wait() Works

The following sequence occurs when wait() is called:

  1. The thread enters a synchronized block or method.
  2. It acquires the object’s monitor lock.
  3. It calls wait().
  4. The thread releases the monitor lock.
  5. The thread enters the WAITING state.
  6. Another thread acquires the same lock.
  7. The second thread calls notify() or notifyAll().
  8. The waiting thread becomes runnable.
  9. Before continuing, it must reacquire the object’s lock.

This mechanism allows threads to cooperate safely without wasting CPU cycles.

Basic Example of wait()


class Shared {

    synchronized void waitingMethod() {

        System.out.println("Thread is waiting...");

        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Thread resumed.");

    }

}

public class Demo {

    public static void main(String[] args) {

        Shared obj = new Shared();

        Thread t1 = new Thread(() -> obj.waitingMethod());

        Thread t2 = new Thread(() -> {

            synchronized(obj) {

                System.out.println("Notifying thread...");
                obj.notify();
            }
        });
        t1.start();
        try {
            Thread.sleep(":111");
        } catch (InterruptedException e) { }
        t2.start();
    }
}

Output

Thread is waiting…
Notifying thread…
Thread resumed.

Explanation:

  • Thread t1 acquires the object’s lock and calls wait().
  • It releases the lock and waits.
  • Thread t2 acquires the lock and calls notify().
  • The waiting thread reacquires the lock and continues execution.

Example Using wait(long timeout)


class Demo {

    public static void main(String[] args) {

        Object lock = new Object();

        synchronized(lock) {

            System.out.println("Waiting...");

            try {
                lock.wait(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Finished waiting.");
        }
    }
}

Output

Waiting…
Finished waiting.

In this example, the thread automatically resumes after approximately three seconds if no notification is received.

wait() with notify()

The notify() method wakes up one thread waiting on the object’s monitor.


class Shared {
    synchronized void produce() {
        try {
            System.out.println("Producer waiting...");
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Producer resumed.");
    }
    synchronized void consume() {
        System.out.println("Consumer notifying...");
       notify();
    }
}

The producer waits until the consumer sends a notification.

wait() with notifyAll()

When multiple threads are waiting on the same object, notifyAll() wakes all waiting threads.


synchronized(lock) {
    lock.notifyAll();
}

Each awakened thread must compete to reacquire the lock before continuing execution.

wait() vs Thread.sleep()

Feature wait() Thread.sleep()
Class Object Thread
Releases Lock Yes No
Requires Synchronization Yes No
Thread State WAITING WAITING
InterruptedException Yes Yes
Used For Thread communication Delaying execution

wait() vs notify() vs notifyAll()

Method Purpose
wait() Makes the current thread wait
notify() Wakes one waiting thread
notifyAll() Wakes all waiting threads

These methods are commonly used together for inter-thread communication.

Real-Life Example

Imagine customers waiting at a restaurant.

  • Customers place their orders.
  • They wait until the food is ready.
  • The chef prepares the food.
  • The waiter announces the order.
  • The waiting customer receives the food and continues eating.

Similarly:

  • wait() = customer waits.
  • notify() = waiter calls one customer.
  • notifyAll() = waiter announces that all pending orders are ready.

Common Use Cases

The wait() method is widely used in:

  • Producer-Consumer problems
  • Thread communication
  • Resource sharing
  • Job scheduling
  • Task coordination
  • Blocking queues
  • Event-driven applications

Common Mistakes

1. Calling wait() Outside a Synchronized Block

Incorrect:


lock.wait();

This throws:


IllegalMonitorStateException

Correct:


synchronized(lock) {
    lock.wait();
}

2. Forgetting to Handle InterruptedException

The wait() method throws InterruptedException.

Always handle it properly.


try {
    wait();
} catch (InterruptedException e) {
    e.printStackTrace();
}

3. Using if Instead of while

Incorrect:


if(condition) {
    wait();
}

Correct:


while(condition) {
    wait();
}

Using a while loop protects against spurious wakeups, where a thread may wake without receiving the expected notification or before the condition is actually satisfied.

4. Forgetting notify()

If no thread calls notify() or notifyAll(), a thread waiting with wait() may remain blocked indefinitely (unless a timeout is used).

5. Using sleep() Instead of wait()

Many beginners confuse these methods.

wait() is intended for communication between threads, whereas Thread.sleep() simply pauses the current thread for a specified duration without releasing any monitor lock.

Best Practices

  • Always call wait() inside a synchronized block or synchronized method.
  • Use a while loop to recheck the waiting condition after waking.
  • Prefer notifyAll() when multiple threads may be waiting.
  • Keep synchronized blocks as small as possible.
  • Avoid unnecessary waiting by checking conditions before calling wait().
  • Handle interruptions appropriately instead of ignoring them.
  • Consider higher-level concurrency utilities from java.util.concurrent for complex applications.

Conclusion

The Java wait() method is a fundamental part of Java’s inter-thread communication mechanism. It allows a thread to release an object’s monitor lock and wait until another thread signals that it can continue. When used together with notify() or notifyAll(), it enables efficient coordination between threads without wasting CPU resources.

Understanding how wait() works, when to use it, and how it differs from Thread.sleep() is essential for writing reliable multithreaded applications. By following best practices—such as calling wait() only within synchronized code and using a while loop to check conditions—you can build thread-safe, efficient, and maintainable Java applications.

Related Java Tutorials