Java 29: synchronized, volatile, Atomic
easy⏱ 5 mincoursejava
synchronized = monitor lock
Every Java object has a monitor. synchronized(obj) { ... } acquires it; leaving the block releases it. synchronized on an instance method locks this; on a static method locks ClassName.class. Gives mutual exclusion + happens-before memory semantics (all writes before release are visible after acquire).
volatile = visibility only
volatile guarantees: (1) reads/writes go to main memory (not a CPU cache), so other threads see the latest value. (2) Ordering — no reordering of volatile reads/writes with surrounding instructions. It does NOT give atomicity for compound ops like count++ (read + increment + write = 3 ops, race window between them).
Atomic = lock-free CAS
AtomicInteger.incrementAndGet() uses compareAndSet in a spin loop: read the current value, try to swap to current+1 atomically. On failure (someone else swapped first), retry. No lock, no blocking. LongAdder (Java 8) scales even better — per-thread cells summed on read.
private final AtomicInteger count = new AtomicInteger();
public void inc() { count.incrementAndGet(); } // atomic, lock-free
public int get() { return count.get(); }
Stress-test three counters
Implement SyncCounter (synchronized inc), VolatileCounter (volatile int, non-atomic count++), AtomicCounter (CAS loop). Run 1000 'increment' simulations with interleaved 'concurrent' runs. Volatile should sometimes lose updates; sync and atomic should always be 1000.
Reach for concurrent collections first
Before using low-level synchronized/volatile, check if a ConcurrentHashMap, ConcurrentLinkedQueue, AtomicReference, or CompletableFuture covers your case. Higher-level tools are easier to get right and usually faster.
Quiz: Double-checked locking
if (instance == null) synchronized(lock) { if (instance == null) instance = new X(); } — does this work? Only if instance is volatile. Without volatile, a partially-constructed X might leak via the first unsynchronized check. The volatile happens-before ensures full construction is visible before publication.