volatile vs synchronized: When to Use Each
You'll learn: When to choose volatile's lightweight visibility guarantee versus synchronized's full atomicity and mutual exclusion.
Understanding the Trade-Off
Both volatile and synchronized solve visibility problems, but they offer different levels of protection at different performance costs.
volatile provides a lightweight guarantee: writes to a volatile variable are immediately visible to all threads. It establishes a happens-before relationship but does not provide atomicity for compound operations or mutual exclusion. Think of it as a "transparent window"—everyone sees the current value, but multiple people can still try to update it simultaneously.
synchronized is heavyweight: it guarantees both visibility and mutual exclusion (only one thread executes the critical section at a time). It makes compound operations atomic. Think of it as a "locked room with a window"—only one person can be inside at a time, and when they leave, everyone outside sees what changed.
When to Use volatile
Use volatile when:
- You're reading/writing a single variable
- Operations are simple assignments (not
count++or check-then-act) - You need visibility guarantees without blocking
private volatile boolean shutdownRequested = false;
// Thread 1
shutdownRequested = true; // Simple write
// Thread 2
while (!shutdownRequested) { // Simple read
// do work
}
When to Use synchronized
Use synchronized when:
- Operations involve multiple steps that must be atomic
- You need mutual exclusion (preventing simultaneous access)
- Compound operations like incrementing, check-then-act patterns
private int count = 0;
public synchronized void increment() {
count++; // Read-modify-write must be atomic
}
Key Takeaway: Use volatile for simple flag variables where visibility is enough; use synchronized when you need atomicity or must protect compound operations from concurrent modification.