Java Thread.sleep in minimal time

The documentation of TimeUnit.sleep (long timeout) describes its argument in this way:

timeout - minimum timeout.

However, I find this - at least on Windows 7 64-bit with the Java 8 141 update - the thread often sleeps 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 document also states that it TimeUnit.sleep()is a convenient wrapper for Thread.sleep, and the latter does not say whether it guarantees to sleep at least the indicated amount.

Is this an API implementation error or is it TimeUnit.sleepand / or Thread.sleepdesigned only for hibernation for approximately, but not at least the specified duration?

+6
1

TimeUnit.sleep() Thread.sleep().

Thread.sleep() , TimeUnit.sleep() , .

+3

All Articles