Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Thread.onSpinWait — a hint for busy-wait loops

Thread.onSpinWait() tells the runtime that a loop is busy-waiting. It may enable an optimization, but it neither replaces synchronization nor guarantees a speedup.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public static void onSpinWait()

while (!ready) {
    Thread.onSpinWait();
}

Thread.onSpinWait() is a static method available since Java 9, taking no arguments and returning void. Call it inside a busy-wait loop. The JVM may use this hint for a processor-dependent optimization; a speedup is not guaranteed.

This is not sleeping or blocking: the loop keeps checking its condition and may consume CPU time. Removing the call must not affect the algorithm's correctness. Use this kind of waiting cautiously when you expect a very short delay.

The method does not provide visibility of shared data. In the example, the volatile write ready = true and a subsequent read of that value establish a happens-before relationship, making the earlier write result = 42 visible. Do not remove volatile on the assumption that Thread.onSpinWait() replaces synchronization.

Examples

public class SpinWaitDemo {
    private static volatile boolean ready;
    private static int result;

    public static void main(String[] args) throws InterruptedException {
        Thread producer = new Thread(() -> {
            result = 42;
            ready = true;
        });
        producer.start();

        while (!ready) {
            Thread.onSpinWait();
        }

        System.out.println(result);
        producer.join();
    }
}

Result

42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources