How can I make a loop that executes about 10000 times per second with regular(!) intervals?
(duplicate of continuous data acquisition from parallel port in Java but that one's hard-to-find and isn't answered and very old)
I looked at Thread.sleep(long millis)
and Thread.sleep(long millis, int nanos)
but Oracle's J2SE virtual machine on Windows always sleeps 1 millesecond longer than what I specify. Besides, the nanos field seems to be rounded up to the next whole millisecond (verified, this is hardcoded in the source code of Thread.java).
Experimantal results:
Thread.sleep(0)
sleeps not (100% cpu)Thread.sleep(1)
sleeps 1.95ms on averageThread.sleep(2)
sleeps 2.95ms on averageThread.sleep(0, 0)
sleeps not (100% cpu)Thread.sleep(0, 1)
sleeps 1.95ms on average
So how can I make a loop that iterates more than even 500 times per second with regular intervals?
Edit: I loosen the 'regular' requirement a little. It is not a big problem if one delay is like 4 times shorter than another delay (ie. jitter is not a problem), as long as the longest delay is deterministic and below 0.1ms. (which isn't the case with ScheduledExecutorService
)