Java Thread.sleep() Method Deep Dive with Examples


This article has been revised to ensure it is up-to-date with the latest Java JDK 21, guaranteeing its completeness and relevance.

If you want to pause (temporarily cease) a particular thread in Java from executing, you can make use of the sleep() static method from the Thread class from java.lang package.



When you peek into the java.lang.Thread class, you will see that you have three overloaded sleep() methods to choose from.

  1. public static void sleep(long millis) throws InterruptedException
  2. public static void sleep(long millis, int nanos) throws InterruptedException
  3. public static void sleep(Duration duration) throws InterruptedException


Some key points to make a note about the sleep methods.

  1. They are static methods, hence belong to the class and are invoked using Thread.sleep().
  2. They do not return any value (void).
  3. Throws a InterruptedException.


Let's take a look at each of them one-by-one with examples.


1. sleep(long millis)

    You can make use of the method to make the currently executing thread sleep for the provided time as milliseconds.

    Example 1: Make current Thread sleep for 1000ms = 1 second

    public class ThreadSleepExample {
    
        public static void main(String[] args) throws InterruptedException {
    
            Thread.sleep(1000);
            System.out.println("I just slept for a second!");
    
        }
    }

    I just slept for a second!

    In the above example, we made the main thread to sleep for 1000ms.


    Example 2: A negative timeout value = IllegalArgumentException

    Note: If you try to add a negative long value, you will get a IllegalArgumentException saying "timeout value is negative".

    public class ThreadSleepExample {
    
        public static void main(String[] args) throws InterruptedException {
    
            Thread.sleep(-100);
    
        }
    }

    Exception in thread "main" 
    
    java.lang.IllegalArgumentException: timeout value is negative
      at java.base/java.lang.Thread.sleep(Thread.java:500)
      at ThreadSleepExample.main(ThreadSleepExample.java:5)

    The max value you can provide is the max value of long which is 9223372036854775807. I am sure there is no use case that needs more time as long max value turns out to be ~290 million years!

    Any value above this value may cause an underflow and thus IllegalArgumentException with a negative value.


2. sleep(long millis, int nanos)

    If you are working with a system where you need to make use of the sleep method for a very short time with high precision then you should make use of this method.

    Some use-case could be real-time or high-frequency trading systems or IOT applications.

    Note: The behavior of this method is subject to the precision and accuracy of the system timers and (thread) schedulers.


    Example 3:

    Thread.sleep(10, 12);

    Note that the second parameter to this method is of type int yet the allowed range is 0-999999, outside this range will result in IllegalArgumentException.

    Thread.sleep(10, -12);

    Exception in thread "main" 
    
    java.lang.IllegalArgumentException: nanosecond timeout value out of range
    
    	at java.base/java.lang.Thread.sleep(Thread.java:546)
    	at ThreadSleepExample.main(ThreadSleepExample.java:6)


3. void sleep(Duration duration)

    This method was added in the Java JDK 19 version. You can make use of the time-based Duration class with time values such as '54.2 seconds'. This method is no-operation (no-op) if the provided duration is negative. The max value of the duration can be MAX_VALUE should be less than 292 years.

    Builder Methods from Duration class.

    of (long amount, TemporalUnit unit)
    ofMillis (long millis)
    ofNanos (long nanos)
    ofMinutes (long minutes)
    ofDays (long days)
    ofHours (long hours)
    ofSeconds (long seconds)
    ofSeconds (long seconds, long nanoAdjustment)

    Example 4:

    System.out.println("Sleeping for 20 mins...");
    Thread.sleep(Duration.ofMinutes(20));

Example of InterruptedException:

    InterruptedException is thrown when a thread that is in a waiting or sleeping state gets interrupted, either before or during its activity.

    Example 5:

    public class InterruptThreadSleepMethodExample {
    
        public static void main(String[] args) {
    
            Thread t1 = new Thread(() -> {
                try {
                    Thread.sleep(10000); //10 seconds
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println("t1 thread interrupted!!");
                }
            });
    
            t1.start();
    
            try {
                Thread.sleep(4000);
                t1.interrupt(); //Interrupt t1 thread
            } catch (InterruptedException e) {
                System.out.println("Main thread interrupted!");
            }
        }
    }
    

    java.lang.InterruptedException: sleep interrupted
    	at java.base/java.lang.Thread.sleep0(Native Method)
    	at java.base/java.lang.Thread.sleep(Thread.java:509)
    	at InterruptThreadSleepMethodExample.lambda$main$0(InterruptThreadSleepMethodExample.java:7)
    	at java.base/java.lang.Thread.run(Thread.java:1583)
    t1 thread interrupted!!


Take-aways:

List of Thread.sleep() methods as of Java JDK 21
  • Thread.sleep() is a simple way to introduce delays without being busy waiting.
  • You can choose from the 3 overloaded sleep() methods from the Java Thread class.
  • Sleep duration is specified in milliseconds, nanoseconds, or using a Duration object.
  • When the thread is sleeping, it doesn't consume CPU resources.
  • Sub-millisecond precision is achievable with Thread.sleep(long millis, int nanos), though the accuracy may be challenging in real-time systems due to system-specific variations.
  • Throws InterruptedException when interrupted.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap