Improving readability using TimeUnit sleep

All of us have seen the following idiom  numerous times in java code.

//Sleep for 6 minutes
Thread.sleep(6*60*1000);

However the above is not readable.
  • When someone is writing code, he has to perform the conversion to milliseconds.
  • While trying to understand the code also, someone has to perform the transformation from milliseconds to familiar seconds and minutes.
java.util.concurrent.TimeUnit class also provides mechanism to sleep which circumvents the above difficulties.
Following is an example of sleep using TimeUnit.
//Sleep for 6 minutes
TimeUnit.MINUTES.sleep(6);
//Sleep for 10 seconds
TimeUnit.SECONDS.sleep(10);
//Sleep for 2 hours
TimeUnit.HOURS.sleep(2);


TimeUnit supports following time units for sleep.
  • DAYS
  • HOURS
  • MICROSECONDS
  • MILLISECONDS
  • MINUTES
  • NANOSECONDS 
  • SECONDS
Internally TimeUnit also invokes Thread.sleep() for sleeping. Following is the code used by sleep() method 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);
    }

This small trick improves the readability of code.

Update -
Reddit discussion for this post

  1. in "Sidebar" view, seems the first link does not work.
    otherwise Topics , view are Great

    ReplyDelete

Post a Comment

Popular posts from this blog

Prefer ThreadLocalRandom over Random

Shortest Distance Graph Algorithms - How do they differ?

Java - One liner to Configure Logging