The 30 second answer
Volatile only guarantees visibility and ordering: every thread sees the latest write to that variable. But count plus plus is a read, an add and a write, so two threads can still lose updates with volatile. AtomicInteger makes the whole increment atomic using compare-and-set, without a lock. So I use volatile for a simple stop flag and atomics for counters; under heavy contention, LongAdder.
volatile boolean running = true; // fine: one writer, others only read
volatile int count; count++; // broken: lost updates under contention
AtomicInteger hits = new AtomicInteger();
hits.incrementAndGet();
hits.updateAndGet(x -> Math.min(x + 1, 100));
hits.compareAndSet(expected, newValue);A write to a volatile field happens-before every later read of that field, so it also safely publishes the writes made before it. It does not make compound operations atomic.
Runnable stop-flag demo. One thread sets the flag, another reads it in a loop:
public class StopFlag {
private static volatile boolean running = true; // remove volatile and the loop may never stop
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
long spins = 0;
while (running) { spins++; } // reads the flag on every pass
System.out.println("worker saw running=false after " + spins + " spins");
});
worker.start();
Thread.sleep(500);
running = false; // volatile write: visible to the worker
worker.join();
}
}With volatile, the write in main happens-before the worker's next read, so the loop ends. Without it, the Java Memory Model gives no such guarantee: the JIT may keep the value in a register or hoist the read out of the loop, and the worker can spin forever.
Atomic classes are built on compare-and-set (CAS): read the value, compute the new one, and swap only if nobody changed it meanwhile; otherwise retry.
Under heavy contention many threads keep retrying the same CAS. LongAdder spreads updates across cells and sums them on read; its Javadoc says it has higher throughput under high contention at the cost of more space. Its sum() is not an atomic snapshot, so use it for statistics, not IDs or sequence numbers.
LongAdder requests = new LongAdder();
requests.increment(); // called from many threads
long total = requests.sum(); // read for metrics; not an atomic snapshotAlternate interview scenarios
"Two threads update different fields of the same object, and results are occasionally inconsistent. What are the Java Memory Model implications?"
First, a correction to the premise: writes to different fields do not interfere with each other at the memory level. JLS §17.6 rules out word tearing, so each field is updated independently. JLS §17.7 lets a non-volatile long or double be written as two 32-bit halves, so a reader can see a torn value. Making the field volatile prevents that. So the real causes are usually one of three things. First, an invariant spans both fields, for example min <= max, and a reader sees one updated field without the other because the two writes are not done together under one lock. Second, a reader has no happens-before edge, such as volatile, synchronized or a final field, so it may see stale or reordered values. Third, the object was published unsafely before its constructor finished. The fix is to guard both fields with the same lock, or to replace the object with an immutable one through a volatile or AtomicReference. I prove it with a concurrency stress test, for example jcstress, rather than by reading the code.
"Explain double-checked locking in a Singleton. Why do you need volatile?"
The pattern checks the field, locks only if it's null, and checks again inside the lock. Without volatile it's broken: instance = new Singleton() is an allocation, a constructor run and a reference write, and those writes can be reordered. Another thread can then see a non-null reference to an object whose fields aren't initialized yet. Since Java 5, a volatile write cannot be reordered with earlier writes, and it happens-before the later read, so the second thread sees a fully built object. In practice I'd rather avoid the pattern: an enum singleton, or a static holder class that the JVM initializes lazily and thread-safely, gives the same laziness without any locking code.
private static volatile Singleton instance;
static Singleton get() {
Singleton s = instance;
if (s == null) {
synchronized (Singleton.class) {
s = instance;
if (s == null) instance = s = new Singleton();
}
}
return s;
}Sources (7)
- JLS 8.3.1.4 volatile Fieldsdocs.oracle.com
- JLS 17.4.5 Happens-before Orderdocs.oracle.com
- AtomicInteger Javadocdocs.oracle.com
- LongAdder Javadocdocs.oracle.com
- JLS 21 §17.4 Memory model, §17.6 Word tearing, §17.7 Non-atomic double and longdocs.oracle.com
- Bacon, Pugh et al.: The "Double-Checked Locking is Broken" Declarationcs.umd.edu
- JLS 21 §12.4.2 Detailed initialization proceduredocs.oracle.com