0

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:

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.

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.

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert