What is adaptive spinning w.r.t lock acquisition?

What exactly is adaptive spinning?

To quote from this Java 6 performance page:

Adaptive spinning is an optimization technique where a two-phase spin-then-block strategy is used by threads attempting a contended synchronized enter operation. This technique enables threads to avoid undesirable effects that impact performance such as context switching and repopulation of Translation Lookaside Buffers (TLBs). It is “adaptive” because the duration of the spin is determined by policy decisions based on factors such as the rate of success and/or failure of recent spin attempts on the same monitor and the state of the current lock owner.

So threads initially attempt to spin a couple of times trying to acquire a lock before actually blocking. Then in the future it uses previous success/fail metrics to adaptively determine whether it should try spinning or blocking. Spinning wastes CPU time while blocking may cause a context switch and the thread may wait for a longer amount of time than necessary. The goal is trying to optimize both of these issues based on past behavior.

For more details, the performance doc references this presentation entitled Synchronization in Java SE 6 (HotSpot) by Dave Dice. The first slide is titled “Contended costs (scalability + latency)”:

  • Context switching is extremely expensive
  • Unbounded spinning is unacceptable
  • Address via adaptive spinning

Later in the presentation there is the slide entitled “Adaptive Spinning”:

  • Spin-then-block strategy
    • Try to avoid context switch by spinning on [multi-processor] systems
  • Spin duration
    • Maintained per-monitor
    • varies based on recent history of spin success/failure ratio
  • Adapts to system load, parallelism, application modality
  • [multi-processor]-polite spinning
  • Avoid spinning in futile conditions (owner is blocked)

Interesting stuff.

Leave a Comment