Java.Multithreading.HappensBeforeExample

public class HappensBeforeExample {
    static int data = 0;
    static volatile boolean ready = false;

    public static void main(String[] args) {
        Thread writer = new Thread(() -> {
            data = 42;        // Step 1
            ready = true;     // Step 2 — volatile write, gurantees to be in main memory
        });

        Thread reader = new Thread(() -> {
            while (!ready) {
                // spin until ready becomes true
            }
            System.out.println("Data = " + data); // Step 3 — guaranteed to print 42
        });

        writer.start();
        reader.start();
    }
}

💡 What Happens Here?

  • ready = true is a volatile write in the writer thread.
  • while (!ready) is a volatile read in the reader thread.

✅ According to the Java Memory Model:

A write to a volatile variable happens-before every subsequent read of that same variable.

That means:

  • data = 42 (even though it’s not volatile) is visible to the reader because it happened-before the ready = true write.
  • Reader is guaranteed to see data == 42.

❌ If ready Were Not Volatile?

Then there’s no happens-before, and the JVM could:

  • Reorder data = 42 after ready = true
  • Keep data in a thread-local cache
  • Reader could see ready == true, but data == 0

💥 Boom — classic concurrency bug.

This entry was posted in Без рубрики. Bookmark the permalink.