Timing in modern OSs is never accurate unless you use a language / framework that was specifically designed for this. However, you can work with reasonable uncertainty on most operating systems. But "reasonable" depends on the problem you are trying to solve.
In Java, Thread.sleep is a very simple implementation that, in my opinion, is used too much. Java offers these basic tools for streaming processing not because they are the best solution, but because they are the main tools. Java also offers many other, more sophisticated tools that can greatly improve your needs.
In the example, if you want โaccurateโ time, you can instead use the ScheduledExecutorService , which uses the OS scheduling service, to offer accuracy of at least milliseconds, and often nanoseconds. Although this is not accurate for the nanosecond (despite the suggestion), it will usually be much more accurate than Thread.sleep. But both of them will not be accurate in a heavily overloaded system. If this is enough for your problem, you should go for it. Otherwise, you need a different language / runtime environment.
source share