Wednesday, April 16, 2014

TimeUnit Enum in Java

In this post, we'll see java.util.concurrent.TimeUnit that helps organize and use time representations that may be maintained separately across various contexts with examples. We'll also see how to use TimeUnit sleep() method in Thread context.

A TimeUnit represents time duration at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units.

The unit of time in TimeUnit can be one of:
  • DAYS : Time unit representing twenty four hours
  • HOURS : Time unit representing sixty minutes
  • MICROSECONDS : Time unit representing one thousandth of a millisecond
  • MILLISECONDS : Time unit representing one thousandth of a second
  • MINUTES : Time unit representing sixty second
  • NANOSECONDS : Time unit representing one thousandth of a microsecond
  • SECONDS : Time unit representing one second

A TimeUnit does not maintain time information, but only helps organize and use time representations that may be maintained separately across various contexts. TimeUnit is an enumeration that is used to specify the resolution of the timing.

Some of the methods in the Java API use specific periods. For example, the sleep() method takes time to sleep in milliseconds.
What if we want to specify the time for thread to sleep in some other unit, say days, seconds, nanoseconds etc. In such case, TimeUnit make it easy.

A TimeUnit is mainly used to inform time-based methods how a given timing parameter should be interpreted.
For exampleIn java.util.concurrent.locks class, there is one method that take TimeUnit as parameter.

The following code will timeout in 50 milliseconds if the lock is not available:
Lock lock = ...;
if (lock.tryLock(50L, TimeUnit.MILLISECONDS))
while this code will timeout in 50 seconds:
Lock lock = ...;
if (lock.tryLock(50L, TimeUnit.SECONDS))

Similar for other concurrent class such as int await(long timeout,TimeUnit unit) in CyclicBarrier, boolean await(long timeout, TimeUnit unit) in CountDownLatch, boolean tryAcquire(long timeout,TimeUnit unit) in Semaphore

Sleep( ) method of TimeUnit
When thread woke up and scheduler did't decide to run it.

TimeUnit.SECONDS.sleep(5) or TimeUnit.MINUTES.sleep(1) will call internally Thread.sleep see the below code of sleep from The only difference we see is readability, it's easier to understand and remove confusion about time conversion.

Nanoseconds to Seconds Conversion

That's why we need to put thread on sleep

Related Post
Five Synchronizers in Java 

If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

No comments:

Post a Comment