synchronized, volatile and the Java Memory Model
synchronized gives mutual exclusion and visibility; volatile gives visibility and ordering without locking. Explaining the difference, and the happens-before rules behind them, is a core Java concurrency interview topic.
What you will learn
- Explain race conditions, visibility and reordering
- Use synchronized methods and blocks correctly
- Know what volatile does and does not guarantee
- Write a correct lazy singleton
Key concepts
Race condition
The result depends on thread timing. count++ is read, add, write: two threads can read the same value and lose an increment.
Visibility
Without synchronization a thread may keep a value in a CPU cache or register and never see another thread's write.
synchronized
Only one thread holds an object's monitor at a time. Entering and leaving also creates happens-before edges, so changes made inside are visible to the next thread that takes the same lock. It is reentrant.
volatile
Every read sees the latest write and stops reordering around it. It does not make compound actions such as count++ atomic.
Step by step
Choosing the tool
- A flag one thread writes and others read (stop, ready) → volatile
- A counter → AtomicInteger or LongAdder
- Several fields that must change together → synchronized or a Lock
- Shared maps → ConcurrentHashMap
- Best of all: immutable objects need no synchronization
Examples
Double-checked locking needs volatile
public final class Config {
private static volatile Config instance;
private Config() { /* load */ }
public static Config get() {
Config c = instance;
if (c == null) {
synchronized (Config.class) {
c = instance;
if (c == null) instance = c = new Config();
}
}
return c;
}
}
// Without volatile another thread could see a non-null reference to a half-built object.
// Simpler: the holder idiom or an enum singleton.Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Show 2 threads each incrementing a shared int 1 million times; fix it three different ways.
- Write a stoppable worker with a volatile boolean flag.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
What is happens-before?
A rule of the Java Memory Model: if action A happens-before B, B sees A's effects. Examples: unlocking a monitor happens-before the next lock of it, a volatile write happens-before later reads of it, Thread.start happens-before the started thread's actions, and a thread's actions happen-before another thread returns from join on it.
synchronized method vs block?
A synchronized instance method locks this (a static one locks the Class object). A block can lock a private final object and cover only the critical lines, which reduces contention and stops outside code from taking your lock.
Summary
Races and visibility bugs need synchronization: synchronized for mutual exclusion and visibility, volatile for visibility of single reads and writes, atomics for counters, and immutability wherever possible.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus