Java Core & JVM (50 Qs)•Part 1: Core Language, Memory Model & Collections (1 - 10)
Explain the Java Memory Model (JMM): `volatile` vs. `synchronized` vs. `AtomicReference`.
junior LevelCode ExamplejavaCore Language
In Simple Words:
volatile: Ensures visibility across CPU core caches and prevents compiler instruction reordering. Writes are immediately flushed to main memory. Does NOT guarantee atomicity for compound operations likecount++.synchronized: Ensures mutual exclusion (only one thread enters critical section at a time) AND memory visibility.Atomic*(e.g.AtomicInteger,AtomicReference): Non-blocking lock-free thread safety using CPU-level CAS (Compare-And-Swap) instructions.
java
public class CounterDemo {
private volatile boolean running = true;
private final AtomicInteger requestCounter = new AtomicInteger(0);
public void increment() {
requestCounter.incrementAndGet(); // Lock-free atomic increment
}
public void stop() {
running = false; // Immediately visible to all reading threads
}
}