Java Concurrency: Memory Model Challenges
[Link]/c/bfca2d43-ba9c-4b87-81c3-c97c0c8542bb
Here's a challenging Java interview question commonly asked at senior/lead Java
developer levels (e.g., at FAANG, fintech, or high-scale systems):
Hard Question: Memory Consistency & Happens-Before in Concurrent Code
Consider the following Java code:
java
class ReorderingDemo {
int x = 0;
boolean flag = false;
public void writer() {
x = 42;
flag = true;
}
public void reader() {
if (flag) {
[Link](x); // What values can be printed?
}
}
}
Two threads:
Thread 1 calls writer()
Thread 2 calls reader()
Question:
1. Is it possible for reader() to print 0 ?
2. What guarantees does the Java Memory Model (JMM) provide here?
3. How would you fix it to guarantee 42 is printed if flag == true ?
4. Bonus: Explain reordering, visibility, and happens-before in this context.
Expected Expert-Level Answer
1. Yes, 0 can be printed — even if flag == true
Due to compiler and CPU reordering, the writes in writer() may be reordered:
java
1/3
flag = true; // moved before
x = 42;
So the reader thread may see flag == true but x == 0 .
This is allowed under the JMM without synchronization.
2. Java Memory Model (JMM) Guarantees
No happens-before relationship between x = 42 and flag = true
Writes to different variables can be reordered unless synchronized
No visibility guarantee across threads without proper synchronization
JLS §17.4.5: "If one action happens-before another, then the first is visible to and ordered
before the second."
3. Fixes (in order of preference)
Option 1: volatile on flag
java
volatile boolean flag = false;
Write to flag happens-before subsequent read of flag
All actions before the write to volatile are visible to threads that read it
So x = 42 happens-before flag = true → visible in reader
Option 2: synchronized blocks
java
public synchronized void writer() { ... }
public synchronized void reader() { ... }
Same monitor → total ordering.
Option 3: AtomicInteger + lazySet / compareAndSet (advanced)
4. Bonus: Key JMM Concepts
Concept Explanation
Reordering Compiler/CPU can reorder instructions if result is same in single thread
Visibility One thread's write may not be seen by another without sync
Happens-Before Partial order: if A →hb B, then A’s effects are visible to B
Volatile rules:
Write to volatile →hb subsequent read of same variable
2/3
All prior writes →hb the volatile write
Follow-up (Even Harder)
"What if x is final ? Does it help?"
No. final fields are safe only in constructors. After construction, no special visibility.
Summary (For Interview)
Issue Cause Fix
x not visible No happens-before volatile flag , synchronized , or Atomic*
This question tests deep JMM understanding, not just synchronized vs volatile .
Let me know if you want another hard question on:
GC tuning
Classloader leaks
Fork/Join vs CompletableFuture
Reactive streams backpressure
Unsafe / VarHandle
JVM internals (JIT, safepoints, etc.)
1.6s
Fast
3/3