I have a java program containing a necessary infinite loop. Obviously, just leaving the loop as-is results in the program using the maximum time given to it by the scheduler, so I'd like to yield the current time slice when no more computation can be done for the time.
I've already tried Thread.yield()
, Thread.onSpinWait()
(Though I'm not sure if that actually does what I think I does), and Thread.sleep(0)
. All are either ignored 99% of the time, or just don't work.
The one thing that does seem to work is Thread.sleep(x)
, which drops my cpu usage from ~100% to ~2%. However, sleeping for a set amount of time seems like a bad idea to me. I'm writing a synth at the moment, and so need my time slice back as soon a possible to refill the audio buffer.
I can't simply increase the size of the audio buffer, as doing so quickly introduces extremely noticeable latency.
The audio buffer already spikes to being 80% empty every 20 or so "write cycles", and I'm worried adding a sleep could require too large an audio buffer to avoid artifacts on weaker systems.
Is there any way to consistently yield my current time slice?