I’m a bit ashamed to write this post. I have been working on Java 5 for well over two years and yet I was unaware of the power of the java.util.concurrent.TimeUnit class. While I have used almost all the other juc classes over this time and subsequently TimeUnit as well (in some of them), I never realized how powerful TimeUnit was on its own.
It all started with my obsession to remove all the checkstyle errors in a project that I have been working on. More than 50% of them turned out to be ‘magic number’ warnings. While some of them were my fault, most of them were due to laziness and then there were some due to Thread.sleep calls in the code. There must be an easy way to get rid of these without actually having to make private static final class members for every sleep value. I looked and looked and looked, nope, nothing.
A couple of days later I stumbled upon TimeUnit.convert method. Using this method
Thread.sleep(10000)
becomes
Thread.sleep(TimeUnit.MILLISECONDS.convert(10, TimeUnit.SECONDS)
or
Thread.sleep(TimeUnit.SECONDS.toMillis(10))
That’s not too bad, but as long as we’re using TimeUnit, you might as well use it the right way by doing
TimeUnit.SECONDS.sleep(10)
There is real value in TimeUnit.convert. It makes conversions very very easy. For example, scheduling a runnable to execute once every 24 hours, on a ScheduledThreadPoolExecutor, after the initial delay will require something like
ScheduledFuture<?> futureTask = service.scheduleAtFixedRate(processor, delaySeconds.getSeconds(), 24 * 60 * 60, TimeUnit.SECONDS);
which can easily be replaced with
ScheduledFuture<?> futureTask = service.scheduleAtFixedRate(processor, delaySeconds.getSeconds(), TimeUnit.DAYS.toSeconds(1), TimeUnit.SECONDS);
Checkstyle doesn’t like the first form.
I have taken a vow to replace as much of my ‘time’ code with TimeUnit code. Better late then never.
No related posts.