What does the volatile keyword do in Java, and does it make count++ safe?
volatile guarantees that a write by one thread is immediately visible to other threads and prevents certain reordering. It does not make compound actions like count++ atomic, so a counter still needs synchronized or AtomicInteger.
Explain it simply
Picture a notice board in the hostel. Normally each student may keep a private photocopy of the notice and never check for updates. volatile forces everybody to read from the real board each time, so a change is seen by all. But reading the board and writing a new number back is still two separate steps, and two students can interleave them.
Example
class Worker implements Runnable {
private volatile boolean running = true; // visible across threads
public void run() {
while (running) { /* do work */ }
System.out.println("stopped");
}
void stop() { running = false; } // other thread's write is seen
}
class BadCounter {
volatile int count = 0;
void inc() { count++; } // read, add, write: not atomic, updates can be lost
}What to say in the interview
"volatile gives visibility and ordering, not atomicity. It is right for a simple status flag written by one thread and read by others. For count++ I need AtomicInteger or a synchronized block, because the increment is three steps: read, add, write. Without volatile, a thread may keep a stale cached copy and a loop may never see the stop flag change."
Common mistakes
- Using volatile on a counter and assuming it is thread-safe.
- Thinking volatile makes a whole object's fields volatile. It applies to the reference only.