Java Concurrency Interview

Atomics and compare-and-swap question 58 of 180 senior

What is false sharing, and how do you fix it?

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.

performance hardware false-sharing

Quiz yourself on Atomics and compare-and-swap Suggest a correction