Video in progress
After adding multi-threaded counters, throughput dropped unexpectedly. If you suspect false sharing, how do you check and fix it?
If fields written by different threads sit in the same 64-byte cache line, the cores keep pulling that line away from each other. I look at the object layout with JOL and at cache misses with perf, and then separate the fields with @Contended, padding, or striping as in LongAdder.
📖 Answer
In false sharing, logically nothing is shared: each thread writes to its own counter. But the CPU works with the cache at the cache line level. If two fields are in one line, when one core writes, the copy on another core is invalidated. As a result the code works correctly, but gets slower as cores are added.
An example:
final class Stats {
volatile long requests; // thread A writes
volatile long errors; // thread B writes, probably in the same cache line
}
To check:
- with JOL (
org.openjdk.jol), look at the fields' offsets:ClassLayout.parseClass(Stats.class).toPrintable(); - on Linux,
perf c2cshows exactly which cache lines are "bouncing" between cores; - in JMH, measure with 1, 2, 4, 8 threads: a drop instead of linear growth is the classic sign.
The fix options:
@jdk.internal.vm.annotation.Contended: it is used inside the JDK; in your own code only with-XX:-RestrictContendedand--add-exports. Often not practical.- Manual padding (7
longfields): it works, but the JVM may reorder fields, so it is done with a parent-child class hierarchy (as in the Disruptor). - The simplest and the right way is ready-made structures:
LongAdderhas@Contendedcells inside, and that is exactly what you use for a counter with many writers.
But first think: is this optimization needed? False sharing is noticeable only in very hot code with millions of writes per second. For metric counters Micrometer itself has solved this problem. Let a profile show it before you write your own structure.
Sign up to mark studied questions and save your progress.