Java · OOP, JVM and backend craft
What is the Java Memory Model?
Short answer
The Java Memory Model defines when writes made by one thread become visible to another. It is a happens-before contract covering visibility and ordering, not the physical layout of heap and stack.
The JMM is the concurrency contract between Java code and the JVM. It allows the compiler, JIT and CPU to reorder and cache operations, then defines which observations are legal. Without a happens-before edge, one thread is not guaranteed to see another thread's writes.
Happens-before edges
- Program order within a single thread
- Unlocking a monitor happens-before a later lock of the same monitor
- A write to a volatile field happens-before a later read of that field
- Thread.start happens-before the started thread's actions, and thread actions happen-before join returning
- Transitivity: if A happens-before B and B happens-before C, then A happens-before C
public class Worker implements Runnable {
private volatile boolean running = true;
public void run() {
while (running) {
doWork();
}
}
public void stop() {
running = false;
}
private void doWork() {
}
}Do not confuse the JMM with runtime memory areas. Heap, stack, metaspace and the program counter are storage regions. The JMM is about the rules for visibility and ordering across threads. final fields also have special safe publication guarantees: a properly constructed object is visible with its final state intact.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What happens-before rules do you rely on most often?
- 2Why can a non-volatile flag loop forever?
- 3Does volatile make a group of updates atomic?
- 4What guarantee do final fields provide during publication?
Say it in the interview
The Java Memory Model is the contract that tells me when one thread is guaranteed to see another thread's writes. It is expressed through happens-before edges: program order, monitor lock and unlock, volatile reads and writes, thread start and join, plus transitivity. It is not the heap and stack layout. If I share mutable state without one of those edges, the JVM may legally cache or reorder the access, so I use synchronisation, volatile or atomics deliberately.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.