OnSpinWait Hint For Busy Loops

Insert Thread.onSpinWait into a bounded spin loop so the CPU gets a hint that the thread is waiting on a flag rather than doing work.

JavaResilience

Code

snippet
import java.util.concurrent.atomic.AtomicBoolean;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        AtomicBoolean ready = new AtomicBoolean(false);

        Thread worker = new Thread(() -> {
            int spins = 0;
            // onSpinWait hints that this thread is waiting, not computing
            while (!ready.get() && spins < 100_000_000) {
                Thread.onSpinWait();
                spins++;
            }
            System.out.println("observed ready: " + ready.get());
            System.out.println("spin rounds: " + spins);
        });

        worker.start();
        Thread.sleep(20);
        ready.set(true);
        worker.join();
        System.out.println("spin hint finished");
    }
}

How it works

Everything happens inside the class Main.

The one repetition in this snippet is the loop while (!ready.get() && spins < 100_000_000).

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

The demo output is labeled (observed ready:, spin rounds:, spin hint finished), so every printed line maps back to its originating operation.

Key statements

Thread worker = new Thread(() -> {
int spins = 0;
// onSpinWait hints that this thread is waiting, not computing
while (!ready.get() && spins < 100_000_000) {
Thread.onSpinWait();
spins++;
}
System.out.println("observed ready: " + ready.get());
System.out.println("spin rounds: " + spins);
});
Thread.sleep(20);

Interactive Tools for This Topic

FAQ

What does OnSpinWait Hint For Busy Loops print when run?
The script runs standalone; its 3 labeled outputs include `observed ready:`, `spin rounds:`, `spin hint finished`.