Please Stop Using Thread.sleep() in Java!

Posted by & filed under , , .

DukeFriendsOk, I need a good moan about this to the extent that it deserves its own blog post, but I had it with the bloody Thread.sleep() method in Java!

I know it was the only way to “sleep” back in the day but seriously, but seriously, we have TimeUnit since JDK 1.5 — and nowadays we’re using Java 8 and Java 9 is already on the horizon, so that argument doesn’t hold anymore.

Every piece of code I look at forces me to do all sorts of mental computations just to figure out what is a simple Thread.sleep() saying.

Here’s a few examples, to support my case (ahem, moan!):

Thread.sleep(10000);

This one is actually simple, but you have to spend time counting the zeros to figure out whether it’s a 10 seconds or a one second sleep. You can argue:

Thread.sleep(10_000);

Might “fix” that — but you still have to do the mental computation of transforming to seconds — it just so happens that it’s an easy one to do quickly in our minds that we don’t even feel it! I would argue though that this is much much quicker to interpret:

TimeUnit.SECONDS.sleep(10);

And while the above is not the best argument, here’s one:

Thread.sleep(3000000);

Now you tell me without having to count the zero’s what the heck is this call doing? And I can tell you it does the same as this:

TimeUnit.MINUTES.sleep(50);

But it’s bloody difficult to read!

Seriously, we had TimeUnit since JDK 1.5 — the days of JDK 1.2 are long gone, so can we please drop the cryptic Thread.sleep() in favour of the TimeUnit approach?