Visibility Problem in Java Multithreading
Fast recall
Quick revision
Core answer
Understanding of Java Memory Model basics—synchronized does more than just prevent simultaneous execution, it also ensures memory consistency.
Thinking synchronized only prevents race conditions through atomicity, without realizing it also solves the visibility problem through memory barriers.
Mention the Java Memory Model (JMM) and the happens-before relationship—synchronized creates ordering guarantees that ensure writes before releasing a lock are visible to reads after acquiring the same lock.
Interview-ready guide
Interview answer
A visibility problem means Thread A changes shared data but Thread B has no synchronization rule requiring it to observe that change. synchronized creates the rule when both sides use the same monitor: A's unlock happens-before B's later lock, so B sees the writes that came before the unlock.
I avoid explaining this as 'the JVM flushes every cache to main memory.' That is a hardware story, not the Java guarantee. The portable rule is happens-before. If the state is a simple stop or publication flag, volatile may express the hand-off. If several fields form one invariant, I protect the complete operation with the same lock.
Visibility Problem in Java Multithreading
Direct Answer
A visibility problem occurs when no happens-before relationship requires one thread to observe another's write. If both paths synchronize on the same monitor, an unlock happens-before a later lock, making earlier writes visible after that acquisition. This is a Java Memory Model guarantee, not a command to flush every hardware cache.
Common Mistakes & Pitfalls
- Synchronizing writes but not reads: Freshers protect the write with synchronized but leave reads unsynchronized—reads will still see stale cached values because they don't acquire the lock that triggers cache invalidation.
- Assuming volatile solves race conditions: Volatile guarantees visibility but not atomicity—count plus plus on a volatile int still has a race condition because it's three operations (read, increment, write).
- Ignoring happens-before: Not realizing that synchronized creates ordering guarantees between threads—writes before releasing a lock are visible to subsequent acquisitions of the same lock.
- Over-relying on eventual consistency: Thinking writes will eventually become visible without synchronization—the JMM provides no time bound, so threads might spin forever seeing stale values.
Check your understanding
Answer these without looking back at the article.
- What is the Java Memory Model?
- What is the happens-before relationship?
- How does volatile solve the visibility problem without atomicity?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.