Video in progress

What is false sharing, how does it affect performance, and how do you detect it?

Two threads write to logically separate variables, but those variables sit in the same 64-byte cache line. Every write invalidates the whole line in the other core's cache, and the code slows down even though it's parallel.

📖 Answer

The processor works with memory not byte by byte but in cache lines (usually 64 bytes). Under the MESI protocol, when one core writes to a line, the copy on the other core becomes invalid and has to be reloaded.

class Counters {
    volatile long produced;   // written by the producer thread
    volatile long consumed;   // written by the consumer thread
}

The two fields sit side by side in one line. The threads never touch each other's data, but the line "ping-pongs" between the cores. In a microbenchmark, code like this can come out several times slower than a version with padding added.

Solutions:

  • inside the JDK there's @jdk.internal.vm.annotation.Contended (LongAdder's Cell and the random fields in Thread are protected with it). To make it work in your own code you need -XX:-RestrictContended and a module export, so it's rarely done in practice;
  • manual padding: put 7 longs around the field. The JVM may reorder fields, so this is often done through an inheritance chain (the Disruptor does it this way);
  • best of all: each thread accumulates its state locally and writes to the shared place only rarely.

It's hard to detect, because the code looks "correct". The signs: throughput doesn't grow when you add threads, there's no lock, and the CPU is busy. On Linux, perf c2c shows HITM events at the cache line level. Comparing a padded and an unpadded variant in JMH is the most reliable confirmation.

In an ordinary CRUD service this is almost never the bottleneck. In places like high-frequency counters, ring buffers and matching engines it's serious.