Advanced concurrency

advconcurrency6JavaMemoryModel

Path
pkg16advconcurrency/advconcurrency6JavaMemoryModel.java
Package
pkg16advconcurrency
Study order
6
Run
Single-file source launch
Command
java pkg16advconcurrency/advconcurrency6JavaMemoryModel.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg16advconcurrency/advconcurrency6JavaMemoryModel.java
1package pkg16advconcurrency;2 3/*4 * advconcurrency6JavaMemoryModel.java5 * -----------------------------------6 * Java Memory Model (JMM): visibility, ordering, and happens-before.7 *8 * DEFINITION:9 *   The JMM defines when writes by one thread are visible to another. Without10 *   proper synchronization, the CPU/cache/compiler can reorder or cache values11 *   in ways that break naive assumptions.12 *13 * KEY POINTS:14 *   - happens-before: if A hb B, then B sees all effects of A.15 *   - volatile: writes are visible immediately to other threads (no stale reads).16 *   - synchronized: unlock hb subsequent lock on same monitor.17 *   - final fields: safe publication after constructor completes.18 *   - Avoid double-checked locking without volatile (classic bug).19 */20public class advconcurrency6JavaMemoryModel {21 22    static class BrokenFlag {23        boolean ready = false;  // NOT volatile — may never be seen by reader24        int value = 0;25    }26 27    static class SafeFlag {28        volatile boolean ready = false;29        int value = 0;30    }31 32    public static void main(String[] args) throws InterruptedException {33        System.out.println("JMM rules (happens-before edges):");34        System.out.println("  - unlock -> lock (same monitor)");35        System.out.println("  - volatile write -> volatile read (same field)");36        System.out.println("  - thread start -> thread actions");37        System.out.println("  - thread actions -> thread join");38 39        SafeFlag safe = new SafeFlag();40        Thread writer = new Thread(() -> {41            safe.value = 42;42            safe.ready = true;   // volatile write — publishes value too43        });44        writer.start();45        writer.join();46 47        if (safe.ready) System.out.println("\nSafeFlag: ready=true, value=" + safe.value);48 49        // Demonstrate volatile vs non-volatile (may not fail on all JVMs — JMM allows stale read)50        BrokenFlag broken = new BrokenFlag();51        Thread w2 = new Thread(() -> {52            broken.value = 99;53            broken.ready = true;54        });55        Thread r2 = new Thread(() -> {56            while (!broken.ready) { /* spin */ }57            System.out.println("BrokenFlag (no volatile): value might be 0 or 99 -> " + broken.value);58        });59        w2.start(); r2.start();60        w2.join(); r2.join();61 62        System.out.println("\nRule: use volatile, synchronized, or atomic vars for cross-thread visibility.");63    }64}