On 21/06/2022 9:35 pm, Сергей Цыпанов wrote:
The takeaway from this exercise is that loops with sleeps can't always be 
replaced by loops that busy-wait.
Functionally the logic is the same, but you can't just ignore the concurrency 
aspects.

Thanks for explanation!

Which indicates yielding is having a similar effect to sleeping - though I 
would expect it to be less pronounced.

May I ask one last question about this: in general case when we don't care 
about particular wait time (like in j.n.Bits.reserveMemory())
should I prefer Thread.yield() over both Thread.sleep() and Thread.onSpinWait() 
providing that Thread.sleep() is expensive
and Thread.onSpinWait() might cause undesirable side effects?

Thread.yield() may also have "undesirable side-effects" as you have no idea for how long the thread that yields will be off-cpu.

If you need to slow down the current thread and guarantee some other thread has a chance to make progress then Thread.sleep is best.

Busy-waits/yields/onSpinWait should only be used to impose very brief pauses on a thread that needs another thread to do something to enable forward progress - e.g for spinlocks on multicore systems. Using them when flow control is needed can be problematic as you found in this test.

Cheers,
David
-----

Regards,
Sergey Tsypanov

Reply via email to