Concurrency: threads share memory on purpose
The naive mental model is broken by caches
Modern CPUs have per-core caches and instruction reordering. Without synchronization, a thread on core A may never see a write that a thread on core B just made to an ordinary field — not out of malice, but because the hardware optimized for speed. The Java Memory Model specifies when one thread's writes become visible to another via happens-before edges.
Tools in order of preference
- Immutable data — no synchronization needed, shareable by construction.
- Higher-level concurrency utilities —
ExecutorService,ConcurrentHashMap,CompletableFuture, structured concurrency (Loom). volatilefields — establish a happens-before for a single variable.synchronizedblocks andReentrantLock— protect critical sections.- Low-level primitives (
VarHandle,Unsafe) — last resort, for library authors.
Takeaways
- Prefer immutability; synchronize only what must mutate.
- Understand the difference between visibility and atomicity.
- Use
java.util.concurrent— very few people get custom locks right.
Enjoying This Lesson?
Your support helps create more comprehensive courses and lessons like this one. Help me build better learning experiences for everyone.
Support Awashyak