volatile vs synchronized in Java
Fast recall
Quick revision
Core answer
volatile gives visibility and ordering for reads and writes of one field but no mutual exclusion. synchronized gives mutual exclusion to code using the same monitor and an unlock-to-later-lock happens-before edge. Use volatile for a suitable publication/state flag, an atomic class for one compound value update, and a lock for a larger invariant.Whether the candidate understands what each mechanism actually guarantees in the Java Memory Model
Thinking volatile is a lighter-weight synchronized that provides the same guarantees but with less overhead
Explain that synchronized solves both visibility and atomicity problems, while volatile only solves visibility
Interview-ready guide
Interview answer
volatile and synchronized solve different problems. A volatile field has cross-thread visibility and ordering semantics, but it does not prevent concurrent execution. That is why volatile int count still cannot make count++ atomic.
A synchronized region allows one owner of the same monitor at a time and orders a later acquisition after the earlier release. It can therefore protect a larger read-modify-write or an invariant across fields. I use volatile for a protocol such as publishing a ready flag, AtomicInteger for one independent counter, and a monitor or lock when several changes must stay consistent together. The decision comes from the operation, not from assuming one keyword is always faster.
volatile vs synchronized in Java
Direct Answer
volatile gives visibility and ordering for reads and writes of one field but no mutual exclusion. synchronized gives mutual exclusion to code using the same monitor and an unlock-to-later-lock happens-before edge. Use volatile for a suitable publication/state flag, an atomic class for one compound value update, and a lock for a larger invariant.
Common Mistakes & Pitfalls
- Calling volatile a faster synchronized: the semantics differ because volatile has no mutual exclusion.
- Using volatile for compound updates:
count++and check-then-act can still race. - Synchronizing different monitors: only code using the same monitor excludes and orders itself.
- Assuming one writer automatically makes volatile sufficient: the protocol may still need a consistent multi-field snapshot.
- Choosing from performance folklore: select the primitive from the invariant and measure afterward.
Check your understanding
Answer these without looking back at the article.
- Is volatile sufficient for implementing a singleton with double-checked locking?
- What is double-checked locking?
- Which is faster: volatile reads or synchronized reads?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.