onSpinWait​() method of Thread class – Java 9

It’s the same (and probably compiles to) as the x86 opcode PAUSE and equivalent the Win32 macro YieldProcessor, GCC’s __mm_pause() and the C# method Thread.SpinWait It’s a very weakened form of yielding: it tells your CPU that you are in a loop that may burn many CPU-cycles waiting for something to happen (busy-waiting). This way, … Read more

Spinlocks, How Useful Are They?

It depends on what you’re doing. In general application code, you’ll want to avoid spinlocks. In low-level stuff where you’ll only hold the lock for a couple of instructions, and latency is important, a spinlock mat be a better solution than a lock. But those cases are rare, especially in the kind of applications where … Read more

How does x86 pause instruction work in spinlock *and* can it be used in other scenarios?

PAUSE notifies the CPU that this is a spinlock wait loop so memory and cache accesses may be optimized. See also pause instruction in x86 for some more details about avoiding the memory-order mis-speculation when leaving the spin-loop. PAUSE may actually stop CPU for some time to save power. Older CPUs decode it as REP … Read more

What exactly are “spin-locks”?

When you use regular locks (mutexes, critical sections etc), operating system puts your thread in the WAIT state and preempts it by scheduling other threads on the same core. This has a performance penalty if the wait time is really short, because your thread now has to wait for a preemption to receive CPU time … Read more