Java - Timer Precision Issue

When you have more experience with Thread.sleep/Object.wait, you will soon realize that this method often sleep more than you want.
Java does not guarantee the resolution archived. Java uses underlying OS interrupt to trigger timed event and this interrupt are often in the resolution of 10ms. For example, System.currentTimeMillis return the clock time in millisecond. However, the update of this clock reference is often same as time interrupt (10ms). 
This issue is a problem for application that requires high timer resolution. 
So, Java provides a switch -XX:ForceTimeHighResolution to force the OS time interrupt to 1ms interval. It will set OS interrupt to 1ms when VM starts and reset to original value when VM exit.
But, it seems that -XX:ForceTimeHighResolution is not perfect and is a use at your own risk switch ( Also, setting OS interrupt to 1ms may have big effect on OS performance. 
In general, you can use System.currentTimeMillis for getting absolute time. If you are calculating elapse time, you should use System.nanoTime
To see your Win OS interrupt/s, do the following:
You can see what interrupt period is being used in Windows by running the perfmon tool. After you bring it up you'll need to add a new item to watch (click the + icon above the graph - even if it appears grayed/disabled). Select the interrupts/sec items and add it. Then right click on interrupts/sec under the graph and edit its properties. On the "data" tab, change the "scale" to 1 and on the graph tab, the vertical max to be 1000. Let the system settle for a few seconds and you should see the graph drawing a steady line. If you have a 10ms interrupt then it will be 100, for 1ms it will be 1000, for 15ms it will be 66.6, etc. Note: on a multiprocessor system show the interrupts/sec for each processor individually, not the total - one processor will be fielding the timer interrupts.


Popular posts from this blog

FFMPEG - Creating timelapse with FFMPEG with JPEG

MP4 File Format Part 1