How accurate is Thread.sleep?

Niklas R. picture Niklas R. · Sep 11, 2013 · Viewed 9.8k times · Source

I'm studying computer hardware where we learn that using a hardware timer gets more accurate results than a software delay. I've written a software delay in assembly for 1 millisecond and I can start a process that repeats every millisecod using this delay and with a counter do something else every 100th millisecond, and this technique would be less accurate than using a hardware timer that I got builtin with my hardware that I'm going to use now.

So I wonder how accurate is the timing that is builtin with Java? We have System.currentTimeMillis and Thread.sleep and these might not use hardware timers, so how accurate are these builtin Java methods compared to a hardware timer?

Answer

DeltaLima picture DeltaLima · Sep 11, 2013

Thread.sleep() is inaccurate. How inaccurate depends on the underlying operating system and its timers and schedulers. I've experienced that garbage collection going on in parallel can lead to excessive sleep.

When doing "real time" simulations you have to correct your main loop for the inaccuracies of sleep. This can be done by calculating the expected time of wake-up and comparing that to the actual time of wake-up and correcting for the difference in the next loop.

If you need better performance, have a look at the Java Real-Time System specification. I haven't used it myself so I can't provide further details.