Video in progress
What does the Java Memory Model guarantee and not guarantee in a program with a data race?
For a program without data races, the JMM gives sequential consistency: the code looks as if it ran in order. If there is a race, only a minimal guarantee remains: values never appear "out of thin air" and safety isn't broken, but the order and visibility of reads can't be predicted.
📖 Answer
The JMM's main contract is called DRF-SC: if no sequentially consistent execution contains a data race, the program only produces sequentially consistent results. A data race is when two threads access the same variable, at least one of them writes, and there's no happens-before between them.
What remains when there is a race:
- no out-of-thin-air values. A value you read is one that someone wrote at some point; it doesn't appear from nowhere. This matters for security: for example, password bytes can't "leak" in from another object.
- writes to fields that are not
long/doubleare atomic. For non-volatilelonganddouble, the spec allows splitting into 32-bit halves (word tearing), although in practice this doesn't happen on a 64-bit HotSpot. - final fields look correct, provided
thisdidn't escape from the constructor.
What is lost:
- if thread A writes two fields in the order
x=1; y=1, B can seey==1butx==0; - different threads can see the same writes in different orders;
- a write may never become visible at all (the JIT hoists the read out of the loop).
The takeaway from an architecture standpoint: a "benign data race", like the String.hashCode cache, is accepted only where it's justified at the level of the JDK authors. In team code the rule should be simple: shared mutable state only through explicit synchronization (a lock, volatile, an atomic, a concurrent collection, an immutable object). In code review I don't accept the argument "there's a race here, but it's harmless" unless it's proven with a jcstress test.
One more subtle point: code that breaks the JMM often still works on x86, because the hardware ordering is strong. When you move to ARM, exactly these bugs show up.
Sign up to mark studied questions and save your progress.