How accurate is Thread.sleep?

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.

Leave a Comment