Thread sleep and precise timing

java, multithreading, sleep, thread-sleep

Solution

Timing in modern OSes is never precise, unless you use a language/framework that was explicitly designed for this. You can however work with a reasonable uncertainty in most operation systems. But "reasonable" depends on the problem you are trying to solve.

In Java Thread.sleep is a very basic implementation that is way too overused in my opinion. Java offers these basic threading tools not because they are the best solution, but because they are basic tools. Java as well offers many other, more sophisticated tools, that might suit your needs much better.

In example if you want "precise" timing, you can instead use a ScheduledExecutorService, which uses the OS scheduling service to offer a precision of at least milliseconds, and often even nanoseconds. Although it is not exact to the nanosecond (despite the offer), it will usually be much more accurate than Thread.sleep. But both will not be accurate on a heavily overloaded system. If this is sufficient for your problem, then you should go with this. Otherwise you need a different language/execution environment.

Problem

I am making a code where I want definite precision in my timing. I use a robot to make some actions, then I use `Thread.sleep(some_time)` for `some_time` to be elapsed between the actions. But I don't get best results because as I search it, `sleep` is not accurate. What would be the best way to accomplish this? I mean simulate `Thread.sleep` with other methods.

Original source

Related problems