[concurrency-interest] ScheduledThreadPoolExecutor schdeuling problem ?
hanson.char at gmail.com
Mon Dec 31 16:17:39 EST 2007
Note System.currentTimeMillis() returns the current time in
milliseconds, whereas System.nanoTime() does NOT. Instead,
System.nanoTime() can only be used to measure elapsed time and is not
related to any other notion of system or wall-clock time.
This means, in the original case, changing the implementation to use
nano-time won't solve the problem. There is simply no way to figure
out the current time in nano second precision. The design of the
is to try to figure out an absolute time in the future to execute by
calculating the difference of the future time from now. But once such
scheduled task is executed, the then current time (in millisec) may
still be before the target future time (also in millisec), even though
the delay was accurate to the highest possible degree (in nanosec).
Hence the problem.
Should the task got executed by the scheduler happened earlier than
the target/absolute time, the proper solution would probably be to
skip the execution but immediately reschedule the task to execute at
the same target/absolute time again (by calculating the difference
between the then current time and the target time, both only available
On Dec 31, 2007 11:28 AM, Doug Lea <dl at cs.oswego.edu> wrote:
> Hanson Char wrote:
> > Interestingly when I changed the test to replace all uses of
> > milli-time with nano-time, the earlier-than-expected problem seems to
> > go away. (Nano-test code below.)
> > The lesson/solution seems apparent. Replace all use of
> > System.currentTimeMillis() with System.nanoTime().
> Yes, It is easily possible for nanoTime-based vs currentTimeMillis-based
> duration estimates to differ once in a while;
> for example, because the underlying currentTimeMillis
> system clock is typically updated less frequently.
> On average they balance out, but
> if you need consistency across all readings, you should rely on nanoTime.
More information about the Concurrency-interest