Java Concurrency Interview

The Java memory model question 19 of 180 senior

What is instruction reordering, and can you observe it from ordinary Java?

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.

memory-model reordering

Quiz yourself on The Java memory model Suggest a correction