Is javax.swing.timer's interval constant?

2019-09-02 17:35发布

问题:

In javax.swing.Timer, we are allowed to set the time interval as such:

int delay = 1000;    //update every 1000 millisecond
Timer t = new Timer(delay, listener);

With the above, I will expect the time delay between each interval to be 1000 millisecond. However I when I use it in a Swing application, the delay for each interval is 1014 to 1015.

When I set the delay to 1. The tested delay is 15 to 16 milliseconds per interval.


I have 2 question with regards to the above Timer behaviour:

Q1: What is causing the additional 14 to 15 milliseconds being added to my interval? Is it the "overhead" needed to run the Swing application?

Q2: Will the time delay be guaranteed as what we have stated in the Timer constructor or timer.setDelay()? I ask this because I know the delay in Thread.sleep(delay) is not guaranteed, and it varies with a range. So, what about javax.swing.Timer?

回答1:

The timer uses a sleep operation which is implemented by the operating system. When you run a 32-bit application on Windows, it uses the Win XP emulator which work the same way as it would on Window XP.

If you use the 64-bit JVM which will take advantages of improvements in the OS clock, it should run with 1 milli-second resolution.

Note: ExecutorService added in Java 5.0 uses System.nanoTime() and LockSupport.parkNanos(n) which shouldn't have this problem at it uses high resolution clock.



标签: java swing timer