Java
wait()
sleep()
Java threading
concurrency

Difference between wait vs sleep in Java

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Java programming, wait() and sleep() are two fundamental methods used for managing the execution of threads. While both serve to pause thread execution, they have distinct purposes and behaviors. Understanding their differences is crucial for effectively implementing concurrency in Java applications. This article explores the technical differences between these two methods, provides sample code for better comprehension, and includes a summary table for quick reference.

Purpose and Use Cases

sleep()

The sleep() method is a static method of the Thread class. It is intended to pause the execution of the current thread for a specified duration of time. The syntax of this method is:

java
public static void sleep(long millis) throws InterruptedException;

Use Cases for sleep()

  • Controlling Execution Timing: Commonly used for adding delays in program execution, such as waiting between retries or creating time intervals.
  • Simulating Network Latency: Useful in testing environments to mimic network delays.
  • Animation Control: Can be used in creating pauses between frames in graphics processing or animations.

wait()

The wait() method, however, is a member of the Object class. It causes the current thread to wait until another thread invokes the notify() or notifyAll() methods on the same object. Here's the basic syntax:

java
public final void wait() throws InterruptedException;

Use Cases for wait()

  • Inter-Thread Communication: Allows threads to communicate over a shared resource.
  • Resource Synchronization: Helps manage thread synchronization, particularly in producer-consumer scenarios.
  • Avoiding Busy Waiting: Uses less CPU resource compared to looping or other wait loops.

Key Differences

Below is a detailed explanation of the main differences between wait() and sleep():

  1. Ownership Requirement
    • sleep(): Does not require ownership of any monitor.
    • wait(): Must be called within a synchronized block, requiring ownership of the object's monitor.
  2. Synchronization Context
    • sleep(): Operates independently of synchronization blocks.
    • wait(): Must be invoked from a synchronized context due to its dependence on the object's monitor.
  3. Notifying Mechanism
    • sleep(): No notification mechanism is necessary as it is time-based.
    • wait(): Necessitates explicit invocation of notify() or notifyAll() to resume execution.
  4. Thread Transition State
    • sleep(): Alters the thread state to TIMED_WAITING.
    • wait(): Alters the thread state to WAITING until a notification is received, or a timeout happens.
  5. Exception Handling
    • sleep(): Throws InterruptedException.
    • wait(): Also throws InterruptedException, but needs to be handled in a synchronized block.

Examples

Example: sleep()

Using sleep() to pause thread execution for 2 seconds:

java
1public class SleepExample {
2    public static void main(String[] args) {
3        try {
4            System.out.println("Thread sleeping...");
5            Thread.sleep(2000);
6            System.out.println("Thread resumed.");
7        } catch (InterruptedException e) {
8            e.printStackTrace();
9        }
10    }
11}

Example: wait()

Using wait() in a synchronous context:

java
1class WaitNotifyExample {
2    private static final Object LOCK = new Object();
3
4    public static void main(String[] args) {
5        Runnable waitTask = () -> {
6            synchronized (LOCK) {
7                try {
8                    System.out.println("Waiting...");
9                    LOCK.wait();
10                    System.out.println("Notified and resumed.");
11                } catch (InterruptedException e) {
12                    e.printStackTrace();
13                }
14            }
15        };
16
17        Runnable notifyTask = () -> {
18            synchronized (LOCK) {
19                System.out.println("Notifying...");
20                LOCK.notify();
21            }
22        };
23
24        Thread waitThread = new Thread(waitTask);
25        Thread notifyThread = new Thread(notifyTask);
26
27        waitThread.start();
28        try {
29            Thread.sleep(1000); // Ensure waitThread runs first
30        } catch (InterruptedException e) {
31            e.printStackTrace();
32        }
33        notifyThread.start();
34    }
35}

Table Summary

Aspectsleep()wait()
Belongs ToThread ClassObject Class
Needs Synchronization?NoYes
Requires Monitor?NoYes
Resume MechanismAutomatic (time-based)Requires notify()/notifyAll()
Changes Thread StateTIMED_WAITING from RunnableTransfers to WAITING state
ExceptionThrows InterruptedExceptionThrows InterruptedException
PurposeTo pause execution for a specified timeSynchronization between threads and resource sharing
UsageDelays, periodical tasksInter-thread communication

Conclusion

Understanding the differences between sleep() and wait() is critical for Java developers working with concurrent programming. While sleep() is straightforward for introducing time delays, wait() offers a more complex synchronization mechanism, allowing threads to pause until specific conditions are met. Knowing when and how to use these methods effectively contributes to better resource management and reduced CPU workload in Java applications.


Course illustration
Course illustration

All Rights Reserved.