Sunday, 26 January 2014

Prefer TimeUnit Sleep over Thread.Sleep - Java Coding Tips

What is TimeUnit in Java
TimeUnit
in Java is a class on java.util.concurrent package, introduced in Java 5 along with CountDownLatch, CyclicBarrier, Semaphore and several other concurrent utilities. TimeUnit provides a human readable version of Thread.sleep() method which can be used in place of former. From long time Thread's sleep() method is standard way to pause a Thread in Java and almost every Java programmer is familiar with that. In fact sleep method itself is a very popular and has appeared on many Java interviews. Difference between wait and sleep is one of the tough Java question to answer. If you have used Thread.sleep() before and I am sure you do, you might be familiar with fact like it's an static method, it doesn't release lock when pausing Thread and it throws InterruptedException. But what many of us doesn't consider a potential issue is readability. Thread.sleep() is an overloaded method and accept long millisecond and long nanosecond, which makes it hard for programmers to find out exactly how many seconds, minutes, hours or day current Thread is sleeping. Look at below example of Thread's sleep() method:

Thread.sleep(2400000);

By just having a cursory glance, can you figure out how long current Thread will wait ? Some of you may be but its hardly readable for many Java programmer and you need to convert milliseconds further into seconds and then into minutes. Let's take a look on another example of Thread.sleep() method which is slightly more readable than previous example.

Thread.sleep(4*60*1000);

This is much better than previous one but still its not perfect and until you are aware that sleep times are in millisecond its not easy to guess that current Thread will wait for 4 minutes. TimeUnit class resolves this issue by providing indicator for DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS and NANOSECONDS. java.util.concurrent.TimeUnit is perfect example of powerful Java Enum. All TimeUnit are Enum instances. Let's see how to sleep Thread for 4 minutes using TimeUnit :

TimeUnit.MINUTES.sleep(4);  // sleeping for 1 minutes

Similarly you can introduce pauses on seconds, minutes and hour level. By looking this code you can find out that, this is much more readable than Thread's sleep method. Remember that TimeUnit.sleep() internally calls Thread.sleep() for sleeping and throws InterruptedException. You can also check JDK code to verify that. Here is a sample code example which demonstrate how to use TimeUnit's sleep() method in Java.

/**
 *
 * Java program to demonstrate how to use TimeUnit.sleep() method in Java.
 * TimeUnit is a new way of introducing pause in Java program.
 * @author Javin
 */

public class TimeUnitTest {

    public static void main(String args[]) throws InterruptedException {

        System.out.println("Sleeping for 4 minutes using Thread.sleep()");
        Thread.sleep(4 * 60 * 1000);
        System.out.println("Sleeping for 4 minutes using TimeUnit sleep()");
     
        TimeUnit.SECONDS.sleep(4);
        TimeUnit.MINUTES.sleep(4);
        TimeUnit.HOURS.sleep(1);
        TimeUnit.DAYS.sleep(1);
    }
}


Apart from sleep() functionality, TimeUnit also provide convenient method to convert time into different Unit. For example if you want to convert seconds into milliseconds than you can use following code :

TimeUnit.SECONDS.toMillis(44)

It will return 44,000. It's readable and convenient way to convert time into different unites e.g. micro seconds, Milli seconds etc.

TimeUnit vs Thread.sleep()

What is TimeUnit class in Java programmingSo far we have discussed benefit of using TimeUnit to improve readability but some time it turns out other way as well. Since Thread.sleep() is been around for years, almost every Java programmer knows about it and by looking Thread.sleep() they come to know that Thread is going to pause. This is not true with TimeUnit class, with two reason first its not very popular at least compare to Thread.sleep() and second it's not in Thread class, much like wait and notify which are also not in Thread class.. Anyway none of these are big issues and it will take some time to be adopted and become an standard way, given the size of Java community around the world.

In Summary prefer TimeUnit.sleep() method if you would like to introduce short pause in your program and other places where you think of Thread.sleep(). It not only improves readability of code but also makes you familiar with java.util.concurrent package, which is key API for concurrent programming in Java.

Other multi-threading and concurrency tutorials from Learn About Linux

No comments:

Post a Comment