Java Volatile vs Synchronized vs Atomic and When to Use Each
Decide between volatile, synchronized and atomic classes for shared state, with the counter example that shows why volatile alone is not enough.

Three tools protect shared state in Java, and each solves a different problem. Choosing the wrong one leads to bugs that pass every test and fail in production. This comparison uses one example, a counter, to show where each tool works and where it quietly does not. It builds on the memory model.
The counter that loses updates
class Counter {
private volatile int count;
void increment() { count++; } // read, add, write: three steps
int get() { return count; }
}Run increment() from ten threads, a thousand times each, and get() will often return less than 10,000. volatile makes each read and write visible, and count++ is a read, an add and a write. Two threads can read the same value and write the same result. Visibility is not atomicity.
Fix 1: synchronized
class Counter {
private int count;
synchronized void increment() { count++; }
synchronized int get() { return count; }
}Only one thread at a time runs inside a synchronized method on the same object, and unlocking publishes the writes to the next thread that locks. It is correct, simple and works for many fields at once. The cost is blocking under contention.
Fix 2: an atomic class
class Counter {
private final AtomicInteger count = new AtomicInteger();
void increment() { count.incrementAndGet(); }
int get() { return count.get(); }
}AtomicInteger uses a CPU compare-and-set instruction in a loop, with no lock. It is atomic for that one variable. It cannot keep two variables consistent with each other.
Fix 3: LongAdder for hot counters
When many threads update a counter and few read it, such as a request count, contention on a single memory location slows AtomicLong. LongAdder spreads updates across cells and sums them on sum():
LongAdder requests = new LongAdder();
requests.increment();
long total = requests.sum();sum() is not an atomic snapshot while updates continue. It is right for metrics and wrong for a limit check.
The comparison
volatile | synchronized | Atomic classes | |
|---|---|---|---|
| Visibility | Yes | Yes | Yes |
| Atomic compound actions | No | Yes | Yes, on one variable |
| Blocks other threads | No | Yes | No |
| Works across several fields | No | Yes | No |
| Typical use | Stop flag, published reference | Invariants over several fields | Counters, sequence numbers |
Choosing
- Is the data immutable or confined to one thread? Then none of these is needed.
- A single flag or reference written by one thread and read by others?
volatile. - One number updated by many threads? Atomic, or
LongAdderfor hot metrics. - Several fields that must change together, or a check-then-act sequence?
synchronizedor aLock. See synchronized blocks and contention. - Many readers and rare writers? Consider a read-write lock.
Check-then-act needs more than visibility
if (!map.containsKey(key)) {
map.put(key, load(key)); // another thread may insert between the two calls
}Even with a ConcurrentHashMap, two calls are two operations. Use the atomic method computeIfAbsent(key, k -> load(k)), which does the check and the insert as one.
Double-checked locking needs volatile
Lazy initialization of a shared object is where volatile earns its place. The check outside the lock avoids contention, and without volatile it is a data race:
public final class Registry {
private static volatile Registry instance;
public static Registry get() {
Registry local = instance;
if (local == null) {
synchronized (Registry.class) {
local = instance;
if (local == null) {
instance = local = new Registry();
}
}
}
return local;
}
}Without volatile, another thread can see a non-null instance whose fields are not yet written, because the constructor's writes and the assignment may be reordered. That thread reads a half-built object. With volatile, the write to instance happens after the constructor completes and is visible to any later read. The simpler alternative is the holder class idiom, where a static nested class holds the instance and the class loader guarantees safe initialization, with no volatile and no lock in the code.
A test that shows the lost update
A race is easy to believe and hard to see. Four threads incrementing a plain counter make the problem visible in under a second:
class Counter {
long value;
void increment() { value++; }
}
Counter counter = new Counter();
Thread[] threads = new Thread[4];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 1_000_000; j++) counter.increment();
});
threads[i].start();
}
for (Thread t : threads) t.join();
System.out.println(counter.value);The expected total is 4,000,000, and a typical run prints a lower number that changes every time. Marking value as volatile does not change that, because value++ is a read, an add and a write, and two threads can read the same value. Only synchronized or an atomic class fixes it. The experiment is worth running once on your own machine, since the size of the loss depends on the core count.
The cost of each tool
The relative cost depends on contention, which is why advice to always use one is wrong.
| Tool | Uncontended | Under heavy contention | Gives |
|---|---|---|---|
volatile read or write | Close to a plain access on x86 | Same | Visibility and ordering for one variable |
AtomicLong | One hardware compare-and-swap | Retries in a loop, throughput drops | Atomic update of one variable |
LongAdder | Slightly more than atomic | Scales with threads | A counter you read rarely |
synchronized | Cheap after biasing was removed, a CAS on the lock word | Threads block and wake | Atomic update of several variables |
ReentrantLock | Similar to synchronized | Offers timeouts and fairness | Same, with more control |
Measure with JMH on the hardware that will run the service. A microbenchmark on a laptop with two threads says little about 32 cores.
Atomicity across variables
Visibility of each field does not give consistency across fields. An invariant that spans two variables, such as a range with low <= high, cannot be kept with two volatile fields, since a reader can see the new low and the old high. Put both into an immutable object and publish it through one volatile or atomic reference:
record Range(int low, int high) { }
private volatile Range range = new Range(0, 10);
void update(int low, int high) {
range = new Range(low, high);
}Readers get a consistent pair every time, because they read the reference once. This replace-the-whole-value pattern is the most useful use of volatile after flags.
Flags and shutdown
The classic correct use is a stop flag: one thread sets it, another polls it. A loop on a plain boolean may never see the change, as the JIT is allowed to hoist the read out of the loop. For work that blocks, interruption is better than a flag, since it wakes a thread that is sleeping or waiting on I/O.
Writing the choice down in the code
Concurrency choices are invisible once the code is written. A one-line comment next to each shared field, naming the mechanism and the reason, helps the next reader: "volatile: single writer, many readers", "guarded by lock", "atomic: independent counter". If a comment says "volatile" and the code does a read-modify-write, the mismatch is visible in review.
Annotations such as @GuardedBy from the JCIP annotations are checked by some static analysis tools, and they turn the comment into a rule that can fail a build.
Where the comparison does not hold
On virtual threads, synchronized blocks that wait for I/O could pin the carrier thread until Java 24, where JEP 491 removed most pinning. Lock-free code is harder to get right than it looks, so reach for the library classes. The [java.util.concurrent.atomic package documentation](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/atomic/package-summary.html) lists the atomics, and the thread basics are in Java threads explained.


