When would you choose volatile over synchronized or an Atomic class, and when is volatile insufficient?
answer
- visibility-only -> volatile
- atomic one-field update -> Atomic/CAS
- multi-field invariant -> synchronized/Lock
- count++ needs Atomic, not volatile
- cost: volatile < atomic < synchronized
basics
~20 sUse volatile when you only need a single field's latest value to be visible across threads and you don't combine reads and writes. Use synchronized or an Atomic class when you need atomic compound updates (like count++) or to coordinate several fields together.
solid answer
~50 svolatile gives visibility and ordering for a single field but no atomicity for compound operations and no mutual exclusion. Choose volatile when one or few threads write a single independent field that many threads read, and a single read or single write is all you need — status flags, a published reference, the double-checked-locking guard. Choose an Atomic class (AtomicInteger, AtomicReference) when you need a lock-free atomic read-modify-write on one variable, such as a concurrent counter via incrementAndGet or a CAS-based update loop. Choose synchronized (or a Lock) when you must update multiple fields together as an invariant, when an operation spans several steps that must be exclusive, or when you need wait/notify coordination. The decision ladder: pure visibility of one field -> volatile; atomic update of one field -> Atomic; multi-field invariant or critical section -> synchronized/Lock. volatile is insufficient the moment correctness depends on a read and a later write being indivisible.
code
java · 23 linesimport java.util.concurrent.atomic.AtomicInteger;
class SharedState {
// volatile: visibility of a single flag
private volatile boolean shutdown;
// Atomic: lock-free atomic counter (a volatile int would lose updates on ++)
private final AtomicInteger hits = new AtomicInteger();
// synchronized: keep two fields consistent together (invariant low <= high)
private int low, high;
void requestShutdown() { shutdown = true; }
boolean isShutdown() { return shutdown; }
void record() { hits.incrementAndGet(); }
synchronized void setRange(int l, int h) {
if (l <= h) { low = l; high = h; } // both updated under one lock
}
synchronized int width() { return high - low; } // readers take the same lock
}go deeper
Knows volatile is for visibility and that counters need something stronger like synchronized or AtomicInteger.
Can apply the decision ladder: volatile for single-field visibility, Atomic for one-field atomic updates, synchronized for multi-field invariants, and names the counter/check-then-act traps.
Reasons about CAS and atomic operations, contention costs (volatile < atomic < synchronized), LongAdder for contended statistics, and the visibility guarantees each tool shares.
Selects mechanisms against a stated consistency/throughput requirement, designs lock-free vs lock-based data structures, and justifies trade-offs at scale.
## Three tools, three jobs Java offers escalating tools for shared mutable state. Picking the wrong one either under-protects (a race) or over-protects (needless contention). ### volatile — visibility + ordering, one field A **volatile** field guarantees: reads see the latest write (visibility), and a happens-before edge orders the write before subsequent reads (ordering). It provides **no atomicity** for read-modify-write and **no mutual exclusion**. It is usually the lightest of the three, because a volatile access never blocks and never retries; its cost is the memory barriers the JVM emits, which depends on the processor. *Use it when:* a single independent field needs to be seen across threads and each operation is a single read or single write. Examples: a `volatile boolean shutdown` flag, a `volatile long lastUpdatedTimestamp`, a one-time-published `volatile Config config`, the `volatile` instance in double-checked locking. ### Atomic classes — lock-free atomic updates, one variable `AtomicInteger`, `AtomicLong`, `AtomicReference`, etc. wrap a single value and offer **atomic compound operations** without a lock. `compareAndSet(expected, newValue)` is **compare-and-set (CAS)**: it writes only if the value still equals the expected one, and reports whether it did. `updateAndGet()` retries such an update when another thread got there first, which is why its Javadoc asks for a side-effect-free function. `incrementAndGet()` and `getAndAdd()` are atomic too; their Java code is a CAS loop, which HotSpot's compilers can replace with a single atomic-add instruction where the processor supports one. *Use it when:* you need an atomic read-modify-write on **one** variable — a concurrent counter, a lock-free stack head, an atomically-swapped reference. For a heavily contended sum used for statistics rather than synchronization control, the `LongAdder` Javadoc recommends it over `AtomicLong`, trading memory for throughput. ### synchronized / Lock — mutual exclusion, multiple fields or steps `synchronized` (or `java.util.concurrent.locks.Lock`) provides **mutual exclusion**: only one thread holds the monitor at a time, and an unlock happens-before every later lock of the same monitor, so it carries visibility too. It is the general tool for keeping **several fields consistent** or performing a **multi-step** operation atomically, and it enables `wait`/`notify` coordination. (An `AtomicReference` to an immutable object holding several values can also replace them together in one `compareAndSet`.) *Use it when:* an invariant spans multiple fields (e.g. `from -= amount; to += amount` in a transfer), a check-then-act must be exclusive, or you need condition waiting. ## The decision ladder 1. Do I only need other threads to *see* the latest value of **one** field, with single reads/writes? -> **volatile**. 2. Do I need an *atomic update* (read-modify-write) of **one** field? -> **Atomic** class. 3. Do I need to update **multiple** fields together, an exclusive multi-step section, or condition waiting? -> **synchronized / Lock**. ## Where volatile is insufficient (classic traps) - **Counters:** `volatile int count; count++;` loses updates — the increment isn't atomic. -> `AtomicInteger`. - **Check-then-act:** `if (instance == null) instance = new X();` across threads is a race even with volatile reads. -> double-checked locking *with* volatile *and* a lock, or the holder idiom. - **Coupled fields:** keeping `low <= high` consistent across two volatile fields fails, because a reader can see a new `low` with an old `high`. -> a lock around both. ## Cost intuition volatile < Atomic (one atomic operation; a CAS-based update may retry under contention) < synchronized (a contended monitor can make threads wait). Reach for the lightest tool that is *correct* — but never trade correctness for cheapness.
- Is volatile cheaper than synchronized, and does that mean you should always prefer it?It is usually cheaper (a volatile access never blocks, while a monitor can), but only prefer it when it is correct. If you need atomic compound updates or multi-field invariants, volatile is wrong regardless of cost — correctness first, then pick the lightest correct tool.
- Why use AtomicInteger instead of synchronized for a counter?AtomicInteger makes the increment one lock-free atomic operation, so no thread ever waits for a monitor, while a contended synchronized block can make threads wait their turn. Both are correct. For a single counter the atomic is the usual choice, and for a heavily contended statistic LongAdder may spread the updates over several variables to reduce contention.
volatile is a public scoreboard everyone can read live; an Atomic is a scoreboard with a built-in 'only change it if it still says X' rule so two people can't clobber each other; synchronized is handing one person the only key to the whole room so they can rearrange several things consistently.
- Using volatile for a counter or any read-modify-write.
- Using volatile to keep two related fields consistent (a reader can see one updated and one stale).
- Claiming synchronized and volatile are interchangeable — of the two, only synchronized gives mutual exclusion.
- Choosing the heaviest tool everywhere out of fear, serializing code that only needed visibility.
- java.util.concurrent.atomic classes
- Java 1.5
context
- 17.4.5. Happens-before Orderdocs.oracle.com
- AtomicInteger (Java SE 27 & JDK 27)docs.oracle.com
- LongAdder (Java SE 27 & JDK 27)docs.oracle.com