/**
 * A single-writer, single-reader publication example. Requires Java 17 or later.
 * Run: java VolatilePublication.java
 * This demonstrates a JMM guarantee; it is not a benchmark or a hardware trace.
 */
public class VolatilePublication {
    private int value;
    private volatile boolean ready;

    private void publish() {
        value = 42;
        ready = true;
    }

    private void read() {
        while (!ready) {
            Thread.onSpinWait();
        }
        // The volatile read observes true, so the earlier value write is visible.
        // There are no subsequent writes to value in this example.
        if (value != 42) {
            throw new AssertionError("Expected 42, observed " + value);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        var state = new VolatilePublication();
        var failure = new java.util.concurrent.atomic.AtomicReference<Throwable>();
        var reader = new Thread(() -> {
            try {
                state.read();
            } catch (Throwable error) {
                failure.set(error);
            }
        }, "reader");
        reader.start();
        state.publish();
        reader.join();
        if (failure.get() != null) {
            throw new AssertionError("Publication check failed", failure.get());
        }
        System.out.println("Reader observed value = 42 after ready = true.");
    }
}
