Code and Snow and Stuff

Musings on software and the quality of the white stuff…

Java Thread Sleep Tip

Hi,

If you often find yourself writing code similar to this:

...
try {
    Thread.sleep(10 * 1000); // sleep for 10 seconds
} catch(final InterruptedException e) {
    ...
}
...

You can make your intent a lot clearer (and IMHO cleaner) by doing this instead:

...
try {
    Thread.sleep(TimeUnit.SECONDS.toMillis(10)); // sleep for 10 seconds
} catch(final InterruptedException e) {
    ...
}
...

The really nice thing about this approach is that you can substitute the SECONDS to anything else, i.e.,

...
try {
    Thread.sleep(TimeUnit.HOURS.toMillis(10)); // sleep for 10 hours!
} catch(final InterruptedException e) {
    ...
}
...

Neato!

-=david=-

About these ads

Written by dharrigan

February 8, 2012 at 2:06 pm

Posted in development, java

Tagged with , , , ,

Follow

Get every new post delivered to your Inbox.

Join 54 other followers