Atomics and compare-and-swap question 58 of 180 senior
What is false sharing, and how do you fix it?
- Two threads reading the same variable
- Correct: Two unrelated variables landing on one 64-byte cache line, so writing one invalidates the other core's copy
- Sharing a lock between unrelated objects
- A JIT deoptimisation
Caches move data in lines, typically 64 bytes. If two threads write two different fields that happen to sit on the same line, the hardware coherence protocol bounces that line between cores as though they were sharing a variable. The program is correct and roughly 2.8x slower, measured.
The fix is padding so the hot fields land on separate lines: @Contended (with
-XX:-RestrictContended, since the annotation is internal), or manual padding fields. This is what
LongAdder's cells and ForkJoinPool's queues do.
The diagnosis matters as much as the fix: it shows up as scaling that gets worse with more threads, with no lock contention anywhere in the profile.
Quiz yourself on Atomics and compare-and-swap Suggest a correction