Locks, conditions and AQS question 42 of 180 senior
What is a spin lock, and when is spinning better than blocking?
- Never, spinning always wastes CPU
- Correct: When the hold time is shorter than a context switch, which is why HotSpot spins before parking
- When there are more threads than cores
- Only in real-time systems
Parking and unparking a thread costs a few microseconds of kernel time plus the cache damage of being rescheduled. If the lock is held for tens of nanoseconds, spinning until it frees is cheaper. HotSpot does adaptive spinning for exactly that reason, and tunes the spin count on how long the lock was held last time.
Spinning is wrong when hold times are long, when there are more runnable threads than cores (you spin
waiting for a thread that is not even running), or on a single core, where it is a guaranteed waste of
a whole slice. Use Thread.onSpinWait() inside the loop: it emits a PAUSE hint that lowers power draw
and helps the sibling hyperthread.
Quiz yourself on Locks, conditions and AQS Suggest a correction