115

If I'm going to have a call to have a Java Thread go to sleep, is there a reason to prefer one of these forms over the other?

Thread.sleep(x)

or

TimeUnit.SECONDS.sleep(y)
Rachel
  • 2,181
  • 2
  • 18
  • 20

2 Answers2

163

TimeUnit.SECONDS.sleep(x) will call Thread.sleep after validating that the timeout is positive. This means that as opposed to Thread.sleep, an IllegalArgumentException will not be thrown when the timeout is negative.

Other than that, the only difference is readability and using TimeUnit is probably easier to understand for non-obvious durations (for example: Thread.sleep(180000) vs. TimeUnit.MINUTES.sleep(3)).

For reference, see below the code of sleep() in TimeUnit:

public void sleep(long timeout) throws InterruptedException {
    if (timeout > 0) {
        long ms = toMillis(timeout);
        int ns = excessNanos(timeout, ms);
        Thread.sleep(ms, ns);
    }
}
Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
assylias
  • 321,522
  • 82
  • 660
  • 783
  • FYI: Selenium project has a Sleeper method that doesn't require catching a exception when using it: https://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/browserlaunchers/Sleeper.html – djangofan Jul 13 '15 at 19:07
  • 2
    I agree. If you want to declare your sleeping time a constant that you can change later, say, from 1 minute to 10 seconds, one solution is `public static final long SLEEPING_TIME = TimeUnit.MINUTES.toMillis(1);`. This allows `Thread.sleep()`but maintains the readability advantage of `TimeUnit`. – Ole V.V. Feb 23 '17 at 21:36
17

They are the same. I prefer the latter because it is more descriptive and allows to choose time unit (see TimeUnit): DAYS, HOURS, MICROSECONDS, MILLISECONDS, MINUTES, NANOSECONDS, SECONDS.

user207421
  • 305,947
  • 44
  • 307
  • 483
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • 9
    argumentative: I prefer the first - I want the thread to sleep, not the `SECONDS` or `MILLISECONDS` [:-) – user85421 Mar 06 '12 at 16:31
  • 4
    @CarlosHeuberger: well, you can read it as *sleep for x `SECONDS`*, but surely it is a matter of taste. On the other hand, note that `sleep()` is `static` method on `Thread` - so one might argue that it isn't clear which thread is suppose to sleep (what does `Thread myThread = ...; myThread.sleep()` mean?) – Tomasz Nurkiewicz Mar 06 '12 at 16:34
  • 12
    @CarlosHeuberger Would be much better to be able write `Thread.sleep(3, TimeUnit.SECONDS)` – assylias Mar 06 '12 at 16:34
  • The are not exactly the same, I've edited the accepted answer to highlight a functional difference (no `IllegalArgumentException` when the timeout is negative). – Ohad Schneider Nov 13 '22 at 00:20