The Java memory model question 19 of 180 senior
What is instruction reordering, and can you observe it from ordinary Java?
- No, the JVM never reorders anything
- Correct: Yes, but almost never from a unit test: the synchronisation that lines two threads up is itself a barrier that hides the effect
- Only on x86
- Only when the JIT is disabled
Compilers, the JIT and the CPU all reorder, as long as a single thread cannot tell. Another thread
can tell. In the classic Dekker probe two threads each write one field and read the other, and 0, 0
is a legal outcome that no interleaving of the source explains.
The interesting part is how hard it is to demonstrate. Lining two threads up requires a latch or a barrier, and that is a memory barrier, which drains the store buffer producing the effect. Measured in the sibling repository, the probe found zero reorderings in 20,000 hand-written attempts and 9,914,377 under jcstress, 3.74% of samples, in a single run.
The lesson is what makes this a senior question. These bugs do not fail in testing. They fail in production, rarely, on someone else's hardware.