Java Memory Model
java memory model (jmm) the java memory model defines how threads interact through memory — what guarantees exist for visibility, ordering and
Introduction
The Java Memory Model defines how threads interact through memory — what guarantees exist for visibility, ordering and atomicity. Without understanding happens-before, you'll write concurrent code that passes tests but fails in production.
Informative example
Happens-before relationships:
// 1. synchronized — unlock happens-before next locksynchronized (lock) { shared = 42; } // write visible after unlock// 2. volatile — write happens-before subsequent readvolatile boolean ready;void writer() { shared = 42; ready = true; }void reader() { if (ready) use(shared); } // guaranteed to see 42// 3. Thread.start / Thread.jointhread.start(); // actions before start visible to new threadthread.join(); // actions in thread visible after join// 4. final fields — safe publication after construction
Best practices
- Document which fields are accessed by multiple threads.
- Use
java.util.concurrentabstractions — they encode correct happens-before. - Don't rely on 'it works on my machine' — the JMM allows surprising reorderings.
Purpose of this lesson
Master Java Memory Model so you can apply it confidently in production Java code, technical interviews, and code reviews.
Step-by-step explanation
- Understand the core idea behind Java Memory Model.
- Walk through the runnable example and tweak it in the playground.
- Apply the pattern in a small Spring Boot or CLI exercise of your own.
- Re-read the common mistakes and interview Q&A to lock the concept in.
Interactive workflow diagram
Identify use case
Recognize when java memory model is the right tool for the problem.
Debugging tips
- Read the full stack trace — Java's exception messages name the offending class and line.
- Reproduce in the smallest possible
main()method before fixing in the real app. - Use IntelliJ's debugger breakpoints and 'Evaluate Expression' rather than scattering
System.out.
Optimization strategies
- Profile before optimizing — JFR (Java Flight Recorder) and async-profiler reveal real hotspots.
- Prefer immutable data and stream pipelines over hand-rolled loops when readability matters.
- Reach for the right JDK collection (ArrayList vs LinkedList vs ArrayDeque) before writing custom data structures.
Enterprise example
Teams at Netflix, Uber and Goldman Sachs apply Java Memory Model daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).
Interview questions & answers
Q1What is happens-before?
Q2Double-checked locking — why volatile?
Summary
In this lesson you learned Java Memory Model — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.