Java Concurrency Interview

Locks, conditions and AQS question 42 of 180 senior

What is a spin lock, and when is spinning better than blocking?

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.

locks performance

Quiz yourself on Locks, conditions and AQS Suggest a correction