Lab 04: Java Memory Model
Overview
Step 1: Java Memory Model — Happens-Before Rules
JMM Happens-Before (HB) partial order:
1. Program order within a thread
2. Monitor lock/unlock: unlock HB → lock
3. volatile write HB → volatile read (same variable)
4. Thread.start() HB → first action in new thread
5. Thread.join() HB → actions after join()
6. Static initializer HB → first use of class
7. Object construction HB → finalizer// Without HB: data race — value may not be visible
int x = 0;
boolean flag = false;
// Thread 1: // Thread 2:
x = 42; // while (!flag) {}
flag = true; // System.out.println(x); // may print 0!
// With volatile: HB guaranteed
volatile boolean vFlag = false;
// Thread 1: // Thread 2:
x = 42; // while (!vFlag) {} // volatile read sees volatile write
vFlag = true; // System.out.println(x); // guaranteed: 42
// (volatile write flushes all prior writes)Step 2: VarHandle — Fine-Grained Memory Access
Step 3: StampedLock — Optimistic Reads
Step 4: LongAdder vs AtomicLong Under Contention
Step 5: False Sharing and @Contended
Step 6: Memory Barriers in Practice
Step 7: Lock-Free Queue Pattern
Step 8: Capstone — VarHandle CAS + StampedLock Demo
Summary
Concept
API
Use Case
Last updated
