Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

sleep

As per this question, Thread.sleep is not necessarily guaranteed to sleep for the duration you specify: it may be shorter or longer.

If you read the documentation for Thread.sleep, you'll see there are no strong guarantees over the exact duration which will be slept. It specifically states the duration is

subject to the precision and accuracy of system timers and schedulers

which is (intentionally) vague but hints that the duration should not be relied upon too heavily.

The granularity of possible sleep durations on a particular operating system is determined by the thread scheduler's interrupt period.

In Windows, the scheduler's interrupt period is normally around 10 or 15 milliseconds (which I believe is dictated by the processor), but a higher period can be requested in software and the Hotspot JVM does so when it deems necessary

Source, emphasis mine

How can I practically guarantee that the sleep duration will be at least the value that I specify?

like image 843
Michael Avatar asked Jul 31 '17 16:07

Michael


People also ask

How do I make my thread sleep for 1 minute?

To make a thread sleep for 1 minute, you do something like this: TimeUnit. MINUTES. sleep(1);

How do I stop sleeping thread?

interrupt() method: If any thread is in sleeping or waiting for a state then using the interrupt() method, we can interrupt the execution of that thread by showing InterruptedException. A thread that is in the sleeping or waiting state can be interrupted with the help of the interrupt() method of Thread class.

Is thread sleep accurate?

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.

How long is thread sleep 1000?

sleep time means more than what you really intended. For example, with thread. sleep(1000), you intended 1,000 milliseconds, but it could potentially sleep for more than 1,000 milliseconds too as it waits for its turn in the scheduler. Each thread has its own use of CPU and virtual memory.


1 Answers

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

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 info is from here

like image 105
Michael Avatar answered Oct 20 '22 16:10

Michael