Improving readability using TimeUnit sleep
All of us have seen the following idiom numerous times in java code.
However the above is not readable.
Following is an example of sleep using TimeUnit.
TimeUnit supports following time units for sleep.
Update -
Reddit discussion for this post
//Sleep for 6 minutes Thread.sleep(6*60*1000);
However the above is not readable.
- When someone is writing code, he has to perform the conversion to milliseconds.
- While trying to understand the code also, someone has to perform the transformation from milliseconds to familiar seconds and minutes.
Following is an example of sleep using TimeUnit.
//Sleep for 6 minutes TimeUnit.MINUTES.sleep(6); //Sleep for 10 seconds TimeUnit.SECONDS.sleep(10); //Sleep for 2 hours TimeUnit.HOURS.sleep(2);
TimeUnit supports following time units for sleep.
- DAYS
- HOURS
- MICROSECONDS
- MILLISECONDS
- MINUTES
- NANOSECONDS
- SECONDS
Internally TimeUnit also invokes Thread.sleep() for sleeping. Following is the code used by sleep() method in TimeUnit
public void sleep(long timeout) throws InterruptedException { if (timeout > 0) { long ms = toMillis(timeout); int ns = excessNanos(timeout, ms); Thread.sleep(ms, ns); }
This small trick improves the readability of code.
Update -
Reddit discussion for this post
in "Sidebar" view, seems the first link does not work.
ReplyDeleteotherwise Topics , view are Great