The Java memory model question 21 of 180 mid
Is long and double assignment atomic in Java?
- Yes, all primitive writes are atomic
- Correct: Not guaranteed for non-volatile
longanddouble: the JLS allows a 64-bit write to be split into two 32-bit halves - Only atomic inside
synchronized - Only on 32-bit JVMs, which no longer exist
The JLS explicitly permits a non-volatile 64-bit write to be treated as two 32-bit writes, so a
reader can observe the high half of one value with the low half of another: a value that was never
written by anyone. Declaring the field volatile makes the access atomic and the tearing
disappears.
In practice every 64-bit HotSpot build writes a long atomically, so this is difficult to reproduce
and often dismissed. It is still the right answer to the question as asked, and it is the honest
reason AtomicLong exists as a type rather than as a convenience wrapper.