Java · OOP, JVM and backend craft
What does volatile guarantee and what does it not?
Short answer
volatile guarantees visibility and ordering for a single field but not atomicity. Reads and writes establish happens-before, so other threads see the latest write.
A volatile write happens-before a later volatile read of the same field. That means the reading thread sees the written value and any writes that happened before it. The compiler and CPU may not reorder around the volatile access in ways that break this guarantee.
public class Publisher {
private int value;
private volatile boolean ready;
public void publish(int next) {
value = next;
ready = true;
}
public void consume() {
if (ready) {
System.out.println(value);
}
}
}Where volatile is the right tool
- A shutdown or cancellation flag read by a worker loop
- Safe publication of an immutable object through a volatile reference
- Double-checked locking for a lazily initialised singleton
- A single writer and multiple readers of one field
volatile does not make count++ atomic. The operation still reads, adds and writes, so two threads can lose updates. Use AtomicInteger, LongAdder or a lock for compound actions. volatile is also not a substitute for protecting a group of related fields unless every read and write follows the same discipline.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why is count++ unsafe on a volatile field?
- 2How does volatile enable double-checked locking?
- 3What is the difference between volatile and synchronized?
- 4When is a volatile reference enough for safe publication?
Say it in the interview
volatile gives visibility and ordering for one field: a write happens-before a later read of the same field, so other threads see the new value and preceding writes. It does not give atomicity, so incrementing a volatile int is still a race. I use it for flags and safe publication, and I use atomics or locks for compound updates. It is cheaper than a lock but only solves the visibility problem.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.