Suppose you had to perform a task with a requirement of doing it fixed number of times (say 20,000
) per second.
How would you time the event?
For 20K times per second you need to busy wait for the next interval. I suggest wait until the next time it should have run to iron out the impact of jitter.
long start = System.nanoTime();
long rate = 20000;
for(long i = 0; ; i++) {
// do something
long end = start + i * 1000000000L / rate;
while(System.nanoTime() < end);
}
The reason you can't use built in Scheduler is that the minimum time slice is 100 micro-seconds which is 10K times per second and the minimum sleep time on many platforms is 1 milli-second.
If you're implementing a control system which requires fixed-interval execution and you want to implement it in Java, read up on real-time Java.
If you just need something executed repeatedly and millisecond-granularity is sufficient, look at Timer or ScheduledThreadPoolExecutor.
If you need finer granularity (i.e., more than 1000 times per second) but you don't strictly require your code to execute at precise intervals, you may be able to get by with Peter Lawrey's busy-wait solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With