Java Coding Tip – Thread.sleep

Calling Thread.sleep method is the most popular approach when a Java programmer wants to suspend the current thread for a specific time.


This method has 2 overloads – the first one has input in milliseconds only, the second one has input in milliseconds and nanoseconds:

// java.lang.Thread

public static void sleep(long millis) throws InterruptedException {...}

public static void sleep(long millis, int nanos) throws InterruptedException {...}

Java coding tip – use TimeUnit

Starting from Java 1.5, there is a java.util.concurrent.TimeUnit enum which provides more readable API than Thread.sleep. This enum has convenient constants like SECONDS, DAYS and so forth. At the same time, TimeUnit has a sleep method which requires parameter as an amount of proper unit:

// java.utils.concurrent.TimeUnit

public void sleep(long timeout) throws InterruptedException {...}

In fact, it’s a human-friendly wrapper around Thread.sleep.

Java code examples

Long story short, just let’s consider code example with both approaches.

Sleep for 3 seconds with Thread.sleep:

try {
    Thread.sleep(3000);
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}

The same but re-written with TimeUnit:

try {
    TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}