How can I guarantee that Thread.sleep will sleep for at least this amount of time?

In accordance with this question, Thread.sleep you will not necessarily sleep during the time you specify: it can be shorter or longer.

If you read the documentation for Thread.sleep, you will see that there are no reliable guarantees regarding the exact duration that will sleep. It specifically states that the duration

taking into account the accuracy and accuracy of system timers and schedulers

which (intentionally) is vague, but hints that duration should not be relied on too much.

The granularity of the possible durations of sleep in a particular operating system is determined by the interruption period of the thread scheduler.

On Windows, the scheduler interruption period is usually around 10 or 15 milliseconds (which I think is dictated by the processor) , but a higher period may be requested in the software, and the JVM Hotspot does this when it sees fit.

Source , my accent

How can I guarantee that the duration of sleep will be at least the value that I will indicate?

+6
source share
1 answer

The best practical solution is to sleep and continue to sleep while there is time:

public void sleepAtLeast(long millis) throws InterruptedException
{
    long t0 = System.currentTimeMillis();
    long millisLeft = millis;
    while (millisLeft > 0) {
       Thread.sleep(millisLeft);
       long t1 = System.currentTimeMillis();
       millisLeft = millis - (t1 - t0);
    }
}

Code and information from here

+4
source

All Articles