Video in progress
When does busy-waiting (spinning) pay off, and what does Thread.onSpinWait() give you?
Spinning means a thread doesn't sleep but checks the condition over and over in a loop. If the wait is very short (under a microsecond), it's cheaper than park/unpark. Thread.onSpinWait() gives the processor a hint that "I'm spinning" (PAUSE on x86), which helps with power use and with the neighboring hyper-thread.
📖 Answer
Putting a thread to sleep and waking it (park/unpark) goes through the OS and takes microseconds. If the condition you're waiting for usually becomes true within a few hundred nanoseconds, falling asleep costs more than the wait itself. That's when you spin:
// wait for another thread to set the volatile flag, which it does very quickly
while (!ready) {
Thread.onSpinWait();
}
onSpinWait() (Java 9+) guarantees nothing, it's just a hint. On x86 HotSpot turns it into the PAUSE instruction: the loop slows down a little, the memory-ordering penalty when leaving the loop is lower, and the second hyper-thread on the same core gets some resources.
When spinning is bad:
- the wait is long or unknown: CPU burns for nothing, and in a container it eats into the CPU limit and leads to throttling;
- there are fewer cores than threads: the spinning thread takes away CPU time from the very thread it is waiting for;
- inside a virtual thread: spinning keeps the carrier busy.
A good pattern in practice is a staged wait: spin a little first, then Thread.yield(), then LockSupport.parkNanos. The JVM does something similar itself: under contention, synchronized doesn't put the thread to sleep right away, it first spins briefly and adaptively.
In business code you almost never need to write a spin yourself. It's for low-latency systems (trading, the Disruptor's BusySpinWaitStrategy), and even there it's used on dedicated cores.
Sign up to mark studied questions and save your progress.