Can a Thread sleep for less than half milli seconds in Java/ Other language?

Viewed 2060

[Edit]: After getting answer I understood its not specific to Java, its related to OS scheduler as well, so adding other tags

Is it possible in Java to make a thread sleep for a nano seconds.

Of course after looking the Thread api where we can pass nano seconds as well in sleep method, the answer could be yes.

But I doubt after looking the implementation/ source of sleep method in Thread class, which is:

public static void sleep(long millis, int nanos)
throws InterruptedException {
    if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative");
    }

    if (nanos < 0 || nanos > 999999) {
        throw new IllegalArgumentException(
                            "nanosecond timeout value out of range");
    }

    if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
        millis++;
    }

    sleep(millis);
}

Now according to the logic it is increasing milli seconds by 1 if the passed nano seconds is more than half milli seconds. But this sounds illogical to me, lets say I have written a code where one of my thread is waiting for say some 40000 nano seconds (in practical scenario it might not be the case) which is less than half milli seconds that means my thread will not wait at all.

Can someone please comment on the same and why this design was decided to wait for milli seconds rather than nano seconds?

Also what would guarantee that the thread wakes up accurately?

1 Answers
Related