Useful TimeUnit enum in java

JDK 1.5 introduces the TimeUnit enum that represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units.

Although it is part of the java.util.concurrent package, the TimeUnit enum is useful in many contexts outside of concurrency.

One of the clear advantages include code readability. Below are few code samples to demonstrate this

Code Sample 1 –
Instead of implementing the convertMillisToDays as below


/**
    * Convert provided number of milliseconds into number of days.
    *
    * @param numberMilliseconds Number of milliseconds to be converted into days.
    * @return Number of days corresponding to number of provided milliseconds.
    */
   private static long convertMilliSecondsToDaysViaSingleMagicNumber(final long numberMilliseconds)
   {
      // 86400000 = 86400 seconds in a day multipled by 1000 ms per second
      return numberMilliseconds / 86400000;
   }

A more readable code would look like


/**
    * Convert provided number of milliseconds into number of days.
    *
    * @param numberMilliseconds Number of milliseconds to be converted into days.
    * @return Number of days corresponding to number of provided milliseconds.
    */
   private static long convertMillisecondsToDaysViaTimeUnit(final long numberMilliseconds)
   {
      return TimeUnit.MILLISECONDS.toDays(numberMilliseconds);
   }

Code Sample 2 –
Instead of calling

Thread.sleep(5000); //Sleeping for 5 seconds

A more readable code would look like

TimeUnit.SECONDS.sleep(5);

The enum constant of theTimeUnit implies the applicable unit of time, so only a base number needs to be provided. The implication here, of course, is that more obvious numbers can be provided for sleeping rather than needing to worry about expressing a large number in milliseconds or even remembering that the method requires the time be specified in milliseconds.

Besides SECONDS, other time unit representations provided by TimeUnit include DAYSHOURS,MICROSECONDSMINUTESNANOSECONDS, and MILLISECONDS.

Two other related useful methods available in TimeUnit are TimeUnit.timedJoin(Thread,long)[convenience method for Thread.join] and TimeUnit.timedWait(Thread,long) [convenience method forObject.wait].

This post is inspired from The Highly Useful Java TimeUnit Enum.

Advertisement

Posted on May 17, 2011, in java and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: