Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
How can you optimize code to avoid false sharing?
False sharing happens when independent variables used by different threads happen to sit in the same CPU cache line, typically 64 bytes. Even though the threads never touch the same variable, one thread's write invalidates the entire cache line in the other thread's cache, forcing an expensive reload from a shared cache level or main memory, purely because of physical proximity in memory.
class Counters { // padding-free: bad volatile long a; // thread A updates this volatile long b; // thread B updates this - likely same cache line as 'a' } class PaddedCounters { // manually padded: good volatile long a; long p1, p2, p3, p4, p5, p6, p7; // padding pushes 'b' onto a new cache line volatile long b; }
The classic fix is padding: adding unused filler fields around a hot field so that each thread's variable lands on its own cache line, guaranteeing that writes to one don't invalidate the other. The JDK itself does this internally, for example in java.util.concurrent.atomic.Striped64, which backs LongAdder.
Java 8 also added @Contended (in jdk.internal.vm.annotation, requiring a JVM flag to take effect outside the JDK itself) to automatically pad a field to its own cache line instead of hand-writing filler fields. In practice, false sharing mainly matters for hot, frequently-written fields under real contention; it's not worth chasing in code that isn't performance-critical.
More Related questions...