TimeUnit class represents time durations at a given unit of granularity and also provides utility methods to convert to different units, and methods to perform timing delays.
TimeUnit is an enum with seven levels of granularity: DAYS, HOURS, MICROSECONDS, MILLISECONDS, MINUTES, NANOSECONDS and SECONDS.
The first feature that I find useful is the convert method. With this method you can say good bye to typical:
private static final int FIVE_SECONDS_IN_MILLIS = 1000 * 5;
to something like:
long duration = TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS);
But also equivalent operations in a better readable method exist. For example the same conversion could be expressed as:
long duration = TimeUnit.SECONDS.toMillis(5);
The second really useful sets of operations are those related with stopping current thread.
For example you can sleep current thread with method:
But you can also use it with join and wait with timeout.
Thread t = new Thread(); TimeUnit.SECONDS.timedJoin(t, 5);
So as we can see TimeUnit class is though in terms of expressiveness, you can do the same as you do previously but in a more fashionable way. Notice that you can also use static import and code will be even more readable.
Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code
Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!
To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.