Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the Timer class in Java sensitive to the system clock? [duplicate]

Tags:

java

timer

This highly voted answer on SO regarding the differences between a Timer and a ScheduledThreadPoolExecutor mentions the following while enumerating the differences:

Timer can be sensitive to changes in the system clock, ScheduledThreadPoolExecutor isn't.

The above is mentioned verbatim inside the great book Java Concurrency in Practice.

I understand the points mentioned in that answer except the above mentioned one. What does it mean to say that Timers can be sensitive to system clock whereas ScheduledThreadPoolExecutors are not?

like image 955
Geek Avatar asked Sep 14 '13 16:09

Geek


1 Answers

Timer uses System.currentTimeMillis(), which represents wall clock time and should never be used for checking relative times such as determining how long something took to run or, in this case, how long to delay before executing a task. System.currentTimeMillis() is affected by things like automatic adjustments to the system clock or even manually changing the system clock. As such, if you call it twice and check the difference between the times you get, you can even get a negative number.

System.nanoTime(), on the other hand, is specifically intended for measuring elapsed time and is what should be used for this sort of thing.

like image 71
ColinD Avatar answered Oct 21 '22 15:10

ColinD