Today I had an interview on which I asked candidate quite usual and basic question about the difference between Thread.sleep()
and Object.wait()
. I expected him to answer something like like this, but he said these methods basically are the same thing, and most likely Thread.sleep
is using Object.wait()
inside it, but sleep
itself doesn't require external lock. This is not exactly a correct answer, because in JDK 1.6 this method have following signature.
public static native void sleep(long millis) throws InterruptedException;
But my second thought was that it's not that ridiculous. It's possible to use timed wait to achieve the same effect. Take a look at the following code snippet:
public class Thread implements Runnable {
private final Object sleepLock = new Object();
// other implementation details are skipped
public static void sleep(long millis) throws InterruptedException {
synchronized (getCurrentThread().sleepLock){
getCurrentThread().sleepLock.wait(millis);
}
}
In this case sleepLock
is an object which is used particularly for the synchronization block inside sleep
method. I assume that Sun/Oracle engineers are aware of Occam's razor, so sleep
has native implementation on purpose, so my question is why it uses native calls.
The only idea I came up with was an assumption that someone may find useful invocation like Thread.sleep(0)
. It make sense for scheduler management according to this article:
This has the special effect of clearing the current thread's quantum and putting it to the end of the queue for its priority level. In other words, all runnable threads of the same priority (and those of greater priority) will get a chance to run before the yielded thread is next given CPU time.
So a synchronized
block will give unnecessary overhead.
Do you know any other reasons for not using timed wait in Thread.sleep()
implementation?