[caption id="attachment_173" align="alignleft" width="584" caption="Thread.sleep() under sleeping"][/caption]
How is sleep implemented in Java anyway?
Avi came asking me if I knew anything about it, I was wondering myself how such a common and important method could be faking in the way shown above. Is it the OS? a Bug in the specific JRE version used? Maybe the API doesn't guarantee milliseconds precision to begin with?
Thinking about all of these factors, we realized that we don't really know how the JVM implements the sleep method functionality, my best guess would have been that the process registers itself in the OS for a wake up call, and the OS wakes the process via a software interrupt. OK, time to search the web.
The following article gives a very detailed answer, explaining that sleep is implemented by a thread giving up its OS scheduling quantum back to the scheduler, on the next execution quantum the thread gets, it has the chance to wake up and continue processing, or again continue sleeping.
Therefore, the accuracy resolution of sleep is directly dependent on the process scheduling resolution of the operating system in usage. Since windows XP process scheduling resolution is roughly 10ms, the sleep mechanism, in the Avi's example, might had preferred to under sleep "a little" rather than oversleeping "a lot", by waking himself in the current scheduling cycle quantum, rather than in the next, future, quantum.
The article also mentions that the inaccuracies are worsened when a process with a higher scheduling priority, than the sleeping process, is in a runnable state.
I assume that, running on a Hypervisor with course grained process scheduling would also produce greater inaccuracies.
You can't rely on the millisecond accuracy of the sleep method. Take a before and after time measurament to find the actual time spent sleeping, in order to avoid ever increasing inacurracies.
Sleep tight :)