How does the JVM instruction getfield work?
04:43 27 Nov 2025

ThreadA getfield Stop.flag is false. At a certain point, another thread modifies Stop.flag to true, but ThreadA getfield Stop.flag always returns false.

I don’t understand: Under the CPU MESI protocol, even if the latest value is not read from memory, ThreadA should still be able to getfield true with the support of MESI. Is it possible that getfield does not read from the CPU cache?

package org.example;

import java.util.concurrent.TimeUnit;

public class TestVolatile2 {
    public static class Stop {
        boolean flag = false;
    }

    public static void main(String[] args) {
        final Stop stop = new Stop();
        // Thread-A
        new Thread("Thread A") {
            @Override
            public void run() {
                Stop s = stop;
                while (!s.flag) { // getfield Stop.flag, but always false. even getfield from cpu caches, but msei sync true. why? getfield always false
                }
                System.out.println(Thread.currentThread() + " stopped");
            }
        }.start();

        // Thread-main
        try {
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread() + " after 1 seconds");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stop.flag = true;
    }
}
java jvm volatile