The Java memory model question 24 of 180 senior
What does the Java memory model promise a correctly synchronized program?
- Nothing extra; you still have to reason about reordering yourself
- Correct: Sequential consistency: with no data races, every execution looks like an interleaving of the source
- That every shared variable behaves as if it were volatile
- That the program cannot deadlock
This is the guarantee that makes the memory model usable, usually called SC-DRF. The JLS defines a program as correctly synchronized when none of its sequentially consistent executions has a data race, and promises that every execution of such a program appears sequentially consistent: some interleaving of each thread's statements, in program order.
The compiler, the JIT and the CPU still reorder, buffer and cache exactly as much as before. The promise
is that a data-race-free program cannot tell. So the practical method is not to reason about fences at
all: make every shared access ordered by happens-before, through a lock, a volatile, a final field
or a java.util.concurrent class, and then reason about interleavings, which is hard enough already.
Two follow-ups separate a strong answer. A program with a data race loses the guarantee, but Java still keeps it memory safe: no torn references, no values out of thin air, no broken type safety. C and C++ are harsher, where a data race is undefined behaviour. And "correctly synchronized" is about data races only, so a race-free program can still have race conditions, such as check-then-act on a concurrent map. Sequential consistency makes the bug reproducible in your head; it does not make it go away.