Java Thread.sleep for minimum time

Klitos Kyriacou :

The TimeUnit.sleep(long timeout) documentation describes its argument thus:

timeout - the minimum time to sleep.

However, I'm finding that — at least on Windows 7 64-bit with Java 8 update 141 — the thread often sleeps for less than the minimum:

public static void main(String[] args) throws InterruptedException {
    final long from = TimeUnit.MILLISECONDS.toNanos(100);
    final long to   = TimeUnit.MILLISECONDS.toNanos(1000);
    final long step = TimeUnit.MILLISECONDS.toNanos(100);
    for (long requestedSleepDuration = from; requestedSleepDuration < to; requestedSleepDuration += step) {
        long sleepStartTime = System.nanoTime();
        TimeUnit.NANOSECONDS.sleep(requestedSleepDuration);
        long sleepEndTime = System.nanoTime();
        System.out.printf(
                "requested=%9d  actual=%9d  %s%n",
                requestedSleepDuration,
                sleepEndTime - sleepStartTime,
                (sleepEndTime - sleepStartTime >= requestedSleepDuration ? "OK" : " Slept less than minimum!"));
    }
}

Typical output:

requested=100000000  actual= 99534864  Slept less than minimum!
requested=200000000  actual=200063646  OK
requested=300000000  actual=299223086  Slept less than minimum!
requested=400000000  actual=399598620  Slept less than minimum!
requested=500000000  actual=499910360  Slept less than minimum!
requested=600000000  actual=600028523  OK
requested=700000000  actual=699604816  Slept less than minimum!
requested=800000000  actual=799230602  Slept less than minimum!
requested=900000000  actual=899490648  Slept less than minimum!

This seems to contradict the documentation. However, the TimeUnit doc also states that TimeUnit.sleep() is a convenience wrapper for Thread.sleep, and the latter doesn't say if it guarantees to sleep at least the specified amount.

Is this an API implementation error, or is TimeUnit.sleep and/or Thread.sleep designed to only sleep for approximately, rather than at least, the specified duration?

UserF40 :

TimeUnit.sleep() delegates to Thread.sleep().

Thread.sleep() is subject to the precision and accuracy of system timers and schedulers, thus TimeUnit.sleep() will not be as accurate as you may need.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=469404&siteId=1