Explain the Java Memory Model, happens-before and the volatile keyword.
Why a memory model exists
CPUs cache values in registers and per-core caches, and both the JIT compiler and the CPU reorder instructions. Without rules, one thread's write might never become visible to another thread, or become visible out of order. The Java Memory Model (JMM, JSR-133) defines when a write by one thread is guaranteed to be visible to a read in another.
Happens-before
If action A happens-before action B, then A's effects are visible to B. The main rules:
- Program order: each action in a thread happens-before later actions in that thread.
- Monitor lock: unlocking a monitor happens-before every later lock of the same monitor.
- volatile: a write to a volatile field happens-before every later read of that field.
- Thread start/join:
t.start()happens-before anything int; everything inthappens-before another thread returns fromt.join(). - Final fields: values of
finalfields set in a constructor are visible to any thread that sees the object reference, ifthisdid not escape during construction. - Transitivity: if A → B and B → C, then A → C. This is what makes "safe publication" work.
volatile
- Guarantees visibility (reads always see the latest write) and ordering (no reordering across the volatile access: writes before a volatile write cannot move after it).
- Does not guarantee atomicity of compound actions.
count++is read-modify-write, so two threads can still lose updates. - Typical uses: stop flags, publishing an immutable object reference, the instance field in double-checked locking.
Example
class Worker implements Runnable {
private volatile boolean running = true; // without volatile the loop may never see false
public void stop() { running = false; }
public void run() { while (running) { doWork(); } }
}
// Safe publication through a volatile write: config fields are visible to readers
private volatile Config current;
void reload() { current = loadConfig(); } // writes inside loadConfig() happen-before readers' readsFollow-up questions interviewers ask
Try answering each one before you open it.
Is count++ on a volatile int thread-safe?
No. It compiles to read, add, write. Two threads can both read 5 and both write 6. Use AtomicInteger.incrementAndGet() (a CAS loop), LongAdder under heavy contention (it spreads updates across cells and sums on read), or a lock if several fields must change together.
Why does double-checked locking need volatile?
instance = new Singleton() is three steps: allocate, run the constructor, assign the reference. Without volatile, the assignment can be reordered before the constructor finishes, so another thread passing the first, unsynchronised null check can see a non-null reference to a half-constructed object. A volatile write forbids that reordering and publishes the fully constructed object.
What is false sharing and how do you avoid it?
CPU caches work in 64-byte lines. If two threads update different variables that sit on the same cache line, each write invalidates the other core's copy, and performance collapses even though there is no logical sharing. Fixes: pad hot fields apart, or use @jdk.internal.vm.annotation.Contended (needs -XX:-RestrictContended). LongAdder and ConcurrentHashMap's counter cells are padded for exactly this reason.