Unknown Java Features Part 2: TimeUnit

Simple Way to use different time units

TimeUnit is the simplest way to work with different time units since Java 5.

Aren’t you annoyed about writing all the time how to convert e.g. minutes to milliseconds? Like “5 * 60 * 1000”?

Sure it’s no rocket science, but it’s difficult to read. The next step is often to extract it as a constant. Then you at least know immediately that’s 15 minutes.

But there is an easier way to express the same thing. The TimeUnit enum. So let’s seeĀ it in action.

package com.effectivejava.timeunit;

import static java.util.concurrent.TimeUnit.MINUTES;

public class Test {

    public static void main(String[] args) {

        long millisOldWay = 15 * 60 * 1000;
        long millisNewWay = MINUTES.toMillis(15);

        System.out.println(millisOldWay);
        System.out.println(millisNewWay);

    }

}

 

With TimeUnit you just express the unit directly and you can still extract it to a constant if needed.

Wanna go to sleep, wait or join?

There are shortcut functions for those as well:

// Thread.sleep for 5 minutes
MINUTES.sleep(5);
// thread.join with 5 minute timeout
MINUTES.timedJoin(thread, 5);
// object.wait with given time
MINUTES.timedWait(obj, 5);

 

TL:TR

TimeUnit is an easy way to convert between time units and express it more clearly. Shortcuts methods like sleep round things up.

This entry was posted in common practice, Java, Unknown feature and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *