Software Development

Using TimeUnit instead of Thread.sleep()

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]

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.

[wp_ad_camp_1]

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like