[concurrency-interest] ScheduledThreadPoolExecutor schdeuling problem ?

Hanson Char 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
CronThreadPoolExecutor

  http://ha-jdbc.sourceforge.net/api/net/sf/hajdbc/util/concurrent/CronThreadPoolExecutor.html

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
in millisec).

Hanson Char

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.
>
>
> -Doug
>
>
>


More information about the Concurrency-interest mailing list