Concurrency · mid
volatile, synchronized and happens-before
volatile gives visibility and ordering but not atomic compound actions. synchronized gives mutual exclusion and visibility. Lazy singletons need volatile or the holder idiom.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Without volatile or a lock, one thread may never see another thread's write (a register copy, or the JIT hoists the read out of a loop).
- volatile: every read sees the latest write, and writes before a volatile write are visible to a thread that reads it. It does not make
count++atomic. - synchronized: one thread at a time (mutual exclusion) plus visibility: work done before releasing a lock is visible to the next thread that takes it.
- Happens-before rules: program order within a thread; unlock before a later lock of the same monitor; a volatile write before later reads;
Thread.startandjoin. - Use volatile for flags and safely published references. Use locks or atomics for check-then-act and read-modify-write.
- Double-checked locking without volatile is broken: the reference can become visible before the constructor's writes, so another thread sees a half-built object.
- Fix 1:
private static volatileinstance. Fix 2: the holder idiom (a static nested class; the JVM initialises a class once). Fix 3: anenumsingleton. - In Spring, beans are singletons already. Mutable fields inside them still need safe updates.
The red pen
Common traps: mistake → fix
Mistake: volatile makes count++ thread-safe
Fix: it is read, add, write: three steps; use an atomic or a lock.
Mistake: Double-checked locking works without volatile
Fix: reordering can expose a half-built object.
Mistake: synchronized only gives mutual exclusion
Fix: it also gives visibility.
Easy to hard
Questions interviewers ask, easy to hard
- What does volatile guarantee and what does it not?
- How is it different from synchronized?
- Is this lazy singleton thread-safe?
- Name three ways to fix double-checked locking.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.