Accurate Sleep for Java on Windows

HaBaLeS picture HaBaLeS · May 5, 2009 · Viewed 20.5k times · Source

Does anyone know a Library which provides a Thread.sleep() for Java which has an error not higher than 1-2 Millisecond?

I tried a mixture of Sleep, error measurement and BusyWait but I don't get this reliable on different windows machines.

It can be a native implementation if the implementation is available for Linux and MacOS too.

EDIT The link Nick provided ( http://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks ) is a really good resource to understand the issues all kinds of timers/sleeps/clocks java has.

Answer

Pool picture Pool · May 5, 2009

To improve granularity of sleep you can try the following from this Thread.sleep page.

Bugs with Thread.sleep() under Windows

If timing is crucial to your application, then an inelegant but practical way to get round these bugs is to leave a daemon thread running throughout the duration of your application that simply sleeps for a large prime number of milliseconds (Long.MAX_VALUE will do). This way, the interrupt period will be set once per invocation of your application, minimising the effect on the system clock, and setting the sleep granularity to 1ms even where the default interrupt period isn't 15ms.

The page also mentions that it causes a system-wide change to Windows which may cause the user's clock to run fast due to this bug.

EDIT

More information about this is available here and an associated bug report from Sun.