This post demonstrates how to use TimeUnit as a replacement to the usual and out-dated way of pausing thread via Thread.sleep().
Stop using Thread.sleep
There are several use-cases where we use Thread.sleep(). For instance, you need check for files in a directory every 5 minutes or so. Implementing something like that using Thread.sleep() looks like this:
[wp_ad_camp_3]
1 2 3 4 5 6 7 | long milliSeconds = 1000; // 1 second try { Thread.sleep(milliSeconds * 60 * 5); } catch (InterruptedException e) { e.printStackTrace(); } |
Ugly, right? Of course, we could use TimeUnit wherever Thread.sleep() is used.
Enter TimeUnit
TimeUnit is a Java Enum. It belongs to the java.util.concurrent package and it is really meant for multi-threading stuff.
[wp_ad_camp_2]
Convert Thread.sleep to TimeUnit
How you want to convert the old codes to use TimeUnit depends on you. Really. The Enum provides a number of Enum types to suit your needs.
- TimeUnit.NANOSECONDS
- TimeUnit.MICROSECONDS
- TimeUnit.MILLISECONDS
- TimeUnit.SECONDS
- TimeUnit.MINUTES
- TimeUnit.HOURS
- TimeUnit.DAYS
For the conversion, we’ll use TimeUnit.MINUTES.
1 2 3 4 5 6 | try { // Sleep for 5 minutes TimeUnit.MINUTES.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } |
[wp_ad_camp_1]