ScheduledThreadPoolExecutor executing a wrong time because of CPU time discrepancy

Posted by richs on Stack Overflow See other posts from Stack Overflow or by richs
Published on 2010-04-30T15:55:28Z Indexed on 2010/04/30 15:57 UTC
Read the original article Hit count: 241

I'm scheduling a task using a ScheduledThreadPoolExecutor object. I use the following method:

public ScheduledFuture<?> schedule(Runnable command, long delay,TimeUnit unit) 

and set the delay to 30 seconds (delay = 30,000 and unit=TimeUnit.MILLISECONDS). Sometimes my task occurs immediately and other times it takes 70 seconds.

I believe the ScheduledThreadPoolExecutor uses CPU specific clocks. When i run tests comparing System.currentTimeMillis(), System.nanoTime() [which is CPU specific] i see the following

schedule: 1272637682651ms, 7858346157228410ns

execute: 1272637682667ms, 7858386270968425ns

difference is 16ms but 4011374001ns (or 40,113ms)

so it looks like there is discrepancy between two CPU clocks of 40 seconds

How do i resolve this issue in java code? Unfortunately this is a clients machine and i can't modify their system.

© Stack Overflow or respective owner

Related posts about java

Related posts about java.util.concurrent