What’s the difference between “wait()” and “sleep()” in Java ?

The wait() and sleep() methods in Java serve different purposes in concurrency and thread management. Here’s a detailed breakdown of their differences:

1. Class and Usage

wait()sleep()
Defined in Object class.Defined in Thread class.
Used for thread synchronization (inter-thread communication).Used to pause the current thread for a specified time.

2. Lock Behavior

wait()sleep()
Releases the object’s lock when called (allows other threads to acquire the lock).Does not release any locks (thread retains ownership of locks).
Must be called within a synchronized block/method (to hold the lock initially).Can be called without synchronization.

3. Awakening Mechanism

wait()sleep()
Wakes up when another thread calls notify()/notifyAll() on the same object, or after a timeout (if specified).Wakes up automatically after the specified time elapses.
Example: wait(1000) waits up to 1 second for notification.Example: sleep(1000) sleeps exactly 1 second.

4. Exception Handling

wait()sleep()
Throws InterruptedException if the waiting thread is interrupted.Also throws InterruptedException if interrupted during sleep.

5. Example Scenarios

Using wait() for Thread Coordination

synchronized (sharedObject) {
    while (conditionNotMet) {
        sharedObject.wait(); // Releases lock and waits
    }
    // Proceed when notified
}

Using sleep() for Timed Delay

try {
    Thread.sleep(2000); // Sleeps for 2 seconds
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}

Key Differences Summary

Aspectwait()sleep()
Lock ReleaseYesNo
Call ContextRequires synchronized block/methodAny context
PurposeThread coordinationTimed pause
Awakening TriggerNotification or timeoutTimeout only
ClassObjectThread

When to Use Which

  • wait(): Use when a thread needs to wait for a condition to be met (e.g., producer-consumer problems).
  • sleep(): Use when a thread needs to pause execution temporarily (e.g., polling with delays).

Common Pitfalls

  • IllegalMonitorStateException: Occurs if wait() is called without holding the object’s lock.
  • Starvation: Misusing sleep() in synchronized blocks can block other threads unnecessarily.

Leave a Reply

Your email address will not be published. Required fields are marked *