Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What does volatile guarantee and what does it not guarantee? Is count++ on a volatile int thread-safe?

volatile guarantees visibility and ordering for one variable: every read sees the latest write to it in the synchronization order, and the JVM may not reorder accesses in a way that breaks the happens-before edge from a write to a later read. It does not make compound actions atomic, so count++ on a volatile int is not thread-safe: it is a read, an add and a write, and two threads can lose an increment. For counters we use AtomicInteger or LongAdder, and we keep volatile for status flags and for publishing references to immutable or safely built objects.

Why this question is asked

volatile is one of the most used and most misunderstood keywords in Java. Developers add it to make a flag work across threads, and then assume it also protects a counter or a check-then-act sequence, which it does not. Interviewers ask this question to see whether we can separate the two properties every shared variable needs, visibility and atomicity, and whether we know which tool provides which. In this answer, we will recap what goes wrong without volatile, look at exactly what volatile promises, show why count++ still loses updates, and see the right tool for each job.

1A Quick Recap: What Goes Wrong Without volatile

Threads in Java share memory, but they do not necessarily see each other's writes immediately, or in the order they were made. The JIT compiler can keep a field in a register and never re-read it, and the CPU can buffer writes or reorder them. The Java Memory Model only guarantees that a write is visible to another thread when a happens-before edge, a rule-based ordering between two actions, connects them. Plain fields shared without synchronization have no such edge.

Two separate properties are at stake. Visibility asks whether another thread sees a write at all, and in what order relative to other writes. Atomicity asks whether a sequence of steps, such as read, modify and write, happens as one indivisible step that no other thread can interleave with. volatile addresses the first, not the second.

2What volatile Guarantees

When a field is declared volatile, every read of it goes to the variable itself, so a loop that checks a volatile flag sees the new value soon after another thread writes it. All volatile accesses form a single total order, the synchronization order, and each read returns the most recent write in that order.

volatile also orders the accesses around it. A volatile write happens-before every later read of the same variable that sees it. Combined with program order, this means that everything a thread wrote before the volatile write is visible to a thread after it reads that value. The JVM therefore will not move earlier writes after the volatile write, or later reads before the volatile read.

Java
class Config {
private Map<String, String> values; // plain field
private volatile boolean loaded; // the publication point
void load() {
values = Map.of("timeout", "30"); // (1) plain write
loaded = true; // (2) volatile write
}
String timeout() {
if (loaded) { // (3) volatile read sees true
return values.get("timeout"); // "30": (1) is visible by transitivity
}
return null;
}
}

Reads and writes of volatile long and double are also atomic, which plain long and double are not guaranteed to be. That is the full list: visibility, ordering around the access, and atomicity of the single read or write.

3What volatile Does Not Guarantee: count++

The expression count++ looks like one operation, but it compiles to three: read count, add one, write count back. volatile makes each of those reads and writes visible, but nothing stops another thread from running its own three steps in between.

Java
class Counter {
private volatile int count;
void increment() { count++; } // read, add, write: three steps
int get() { return count; }
}
Counter c = new Counter();
Runnable task = () -> { for (int i = 0; i < 100_000; i++) c.increment(); };
Thread a = new Thread(task), b = new Thread(task);
a.start(); b.start(); a.join(); b.join();
System.out.println(c.get()); // often less than 200000, e.g. 137512
Step throughHow an increment is lost
Thread Acount (volatile)Thread B
read 5
read 5
write 6
write 6
count is 6, not 7

5 messages in order. Play them, or step through them one at a time.

Each step is visible, but the read-add-write sequence is not atomic.

The lost update happens like this. Thread A reads 5. Thread B reads 5. A writes 6. B writes 6. Two increments happened, but the counter moved by one. volatile made sure both threads read the latest value at the moment they read it, but the value was stale by the time they wrote. The same problem affects any check-then-act sequence on a volatile, such as if (!started) { started = true; init(); }, where two threads can both see false and both run init().

4The Right Tool for Counters

For a counter we need atomicity, and the atomic classes provide it with a single CPU instruction or a compare-and-set loop, without locks.

Java
AtomicInteger count = new AtomicInteger();
count.incrementAndGet(); // atomic read-add-write
// same two-thread test as above prints 200000
LongAdder hits = new LongAdder();
hits.increment(); // spreads updates over cells under contention
long total = hits.sum(); // 200000 after the same test
AtomicBoolean started = new AtomicBoolean();
if (started.compareAndSet(false, true)) init(); // only one thread runs init()

AtomicInteger is the general choice and also supports compareAndSet and updateAndGet for other read-modify-write steps. LongAdder is better for a counter that many threads update often but that is read rarely, such as a metrics counter, because it keeps several internal cells and only adds them up in sum(), which avoids contention on a single memory location. For updates that involve several fields together, we need a lock or a single immutable object swapped through an AtomicReference.

5Where volatile Fits

volatile is the right tool when the variable is written as a whole value that does not depend on its previous value, and when no invariant links it to other variables. The classic cases are a status flag such as running or shutdownRequested, written by one thread and read by others, and a reference to an immutable or fully built object, such as a configuration snapshot that is replaced as a whole.

Choosing between volatile, atomics and locks
NeedToolWhy
Stop flag read by a workervolatile booleanSingle independent value
Publish a new config snapshotvolatile reference to immutable MapWhole value replaced at once
Counter, many writersAtomicInteger or LongAdderRead-modify-write must be atomic
Run init() onceAtomicBoolean.compareAndSetCheck-then-act must be atomic
Two fields kept consistentsynchronized or a lockInvariant spans several variables

6Follow-up questions

Is volatile slower than a plain field?

A little. On x86, a volatile read costs about the same as a plain read, and a volatile write adds a barrier that typically costs tens of cycles. On ARM, both reads and writes use ordering instructions. The bigger cost is that the JIT cannot keep the value in a register or reorder around it. For flags and occasional publication, this is negligible.

Does volatile on an array make its elements volatile?

No. It makes the reference to the array volatile, not the elements. Writing arr[3] = 7 is a plain write. For per-element volatile semantics we use AtomicIntegerArray, AtomicReferenceArray, or a VarHandle obtained with MethodHandles.arrayElementVarHandle.

Can volatile replace synchronized?

Only when the shared state is a single variable written independently of its old value. As soon as we read, decide and write, or keep two fields consistent, we need atomicity, which only atomics or locks provide. synchronized gives both visibility and mutual exclusion; volatile gives visibility only.

7Conclusion

In this answer, we separated visibility from atomicity. volatile gives visibility and ordering for one variable: reads see the latest write in the synchronization order, and writes made before a volatile write are visible to a thread that reads it. It does not make compound actions atomic, so count++ on a volatile int loses updates. Counters belong in AtomicInteger or LongAdder, check-then-act in compareAndSet or a lock, and volatile is right for status flags and for publishing references to immutable or safely built objects.

What to say in the interviewAbout 90 seconds aloud

Open with

volatile gives two things for a single variable. Visibility: a read always sees the latest write in the synchronization order, so the JIT cannot cache the value in a register.

Then, if they want more

And ordering: a volatile write happens-before every later read that sees it, so everything the writer did before the write is visible to the reader after the read. It also makes reads and writes of long and double atomic.

What it does not give is atomicity of compound actions. count++ on a volatile int is a read, an add and a write, so two threads can both read 5 and both write 6, and an increment is lost. The same goes for check-then-act code like if not started then start.

For counters I use AtomicInteger, or LongAdder when many threads update and reads are rare, like metrics, because it spreads contention across cells. For a one-time initialisation I use compareAndSet on an AtomicBoolean. When two or more fields must stay consistent, I use a lock or swap one immutable object through an AtomicReference.

Where volatile fits well is a status flag, like a stop flag written by one thread and read by a worker, or a reference to an immutable or fully built object, such as a configuration snapshot that gets replaced as a whole.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
JLS chapter 17, Threads and Locks
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What does volatile guarantee and what does it not guarantee? Is count++ on a volatile...": https://scrivio-interview-library.netlify.app/java/java-memory-model/842d84125e/