Skip to main content
← PROBLEMS / CONCURRENCY
An end-to-end domain learning journey

Eliminating CPU Cache-Line
False Sharing.

When 8 threads increment adjacent slots in a long[8] array, all 8 counters share one 64-byte CPU cache line, causing MESI Read-For-Ownership (RFO) bouncing that collapses throughput from 800M to 25M ops/sec; padding/striping via LongAdder restores linear scaling.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When 8 threads increment adjacent slots in a long[8] array, all 8 counters share one 64-byte CPU cache line, causin, separate per-thread hot counters onto distinct 64-byte cache lines using LongAdder or @Contended padding to eliminate cross-core MESI RFO invalidations.

TL;DR30-second simplified summary
▾

Core Mechanics: Modern x86_64 CPUs transfer memory between L1/L2 caches and RAM in 64-byte cache lines, not individual 8-byte longs. A long[8] array occupies 64 contiguous bytes—fitting all 8 thread counters on a single cache line.

Visual & Structural Flow: Depicts False Sharing on long[8] (1 Cache Line) vs. Padded Stripes (Core 0 (idx 0) -> MESI Interconnect -> Core 1 (idx 1)); Thread-Local L1 Cache Lines via LongAdder / 64B Stride (Core 0..7 -> L1 Cache Line 0 -> L1 Cache Line 1 -> Scraper (100ms)).

Trade-Offs & Production: Switching from long[] to AtomicLong[] or separate volatile long c0, c1... fields does not fix false sharing: Adjacent Heap Layout: volatile long fields in the same. High-frequency Java telemetry engines eliminate false sharing cleanly in JDK 17+: java.util.concurrent.atomic.LongAdder: Uses internal @Contended-padded Cell stripes.

Failure Modes & Application: Eliminating false sharing is a staple of low-latency infrastructure: LMAX Disruptor Ring Buffer: Padding Sequence cursors (p1..p7) so producer and consumer heads never share a cache line.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why 64-byte cache-line false sharing kills lock-free scaling.

Why this matters: The mechanism: understand how Why 64-byte cache-line false sharing kills lock-free scaling works from first principles.

Modern x86_64 CPUs transfer memory between L1/L2 caches and RAM in 64-byte cache lines, not individual 8-byte longs.

A long[8] array occupies 64 contiguous bytes—fitting all 8 thread counters on a single cache line.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

What happens during MESI RFO cache-line ping-ponging.

Why this matters: The problem: see what breaks without What happens during MESI RFO cache-line ping-ponging under real concurrency or scale.

When Core 0 writes counters[0] and Core 1 writes counters[1] concurrently:

  1. Cache-Line Ownership Theft: Core 0 transitions the shared 64-byte line to Modified, invalidating Core 1's copy.
  2. HITM Stall Cycles: Core 1 stalls waiting to fetch the Modified line (HITM in perf c2c) over the inter-core mesh.
  3. Serialized Execution: Instead of 8× parallel speed, all 8 cores serialize on one cache line.
MESI Coherence Ping-Pong

False Sharing on long[8] (1 Cache Line) vs. Padded Stripes

Core 0 (idx 0)MESI InterconnectCore 1 (idx 1)1. Write counters[0] -> RFOinvalidate2. Invalidate L1 line (idx 1lost!)3. Write counters[1] -> HITMstall!4. Fix: pad 64B / LongAdder -> L1 local

Padding each counter to >= 64 bytes (or using LongAdder) keeps each core's writes in its own L1 cache line.

Engineering Decision Framework
Problem
How to implement Eliminating CPU Cache-Line False Sharing without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When 8 threads increment adjacent slots in a long[8] array, all 8 counters share one 64-byte CPU cache line, causin, separate per-thread hot counters onto distinct 64-byte cache lines using LongAdder or @Contended padding to eliminate cross-core MESI RFO invalidations.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Eliminating CPU Cache-Line False Sharing experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive solution (and why AtomicLong[] or volatile fields still suffer).

Why this matters: The problem: see what breaks without Naive solution under real concurrency or scale.

Switching from long[] to AtomicLong[] or separate volatile long c0, c1... fields does not fix false sharing:

  • Adjacent Heap Layout: volatile long fields in the same object sit side-by-side in memory on the same 64-byte line.
  • AtomicLong Array Density: Contiguous AtomicLong references/objects can still share cache lines, and AtomicLong CAS retries under contention.
Request & State Flow

Naive solution (and why AtomicLong[] or volatile fields still suffer)

App WorkerSingleflight / L1Redis L2Origin DB1. GET key (coalesce duplicates)2. Check L2 distributed cache3. Single origin query on miss4. Populate cache with jitteredTTL
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: Striped LongAdder / 64-Byte Padded Cells.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

High-frequency Java telemetry engines eliminate false sharing cleanly in JDK 17+:

  • java.util.concurrent.atomic.LongAdder: Uses internal @Contended-padded Cell stripes hashed by thread probe; each thread increments its own 64-byte-isolated Cell in < 5 ns amortized, and the 100 ms scraper calls .sum() to aggregate.
  • Explicit 64-Byte Stride / @Contended: When indexing by fixed worker ID (0..7), pad each slot to 64 bytes (stride of 8 longs = 64 bytes, or 16 longs = 128 bytes to defeat hardware spatial prefetchers) with zero JVM flags required.
  • Verification: Validate with JMH + perf c2c (L1-dcache-load-misses and HITM drop by > 95%).
Cache-Line Isolation

Thread-Local L1 Cache Lines via LongAdder / 64B Stride

Core 0..78 writer threadsL1 Cache Line 064B padded Cell[0]L1 Cache Line 164B padded Cell[1]Scraper (100ms)sum() across cells

1.LongAdder Stripes: Maintains @Contended-padded Cell[] so writers never share cache lines.

2.128B Stride Option: Using stride=16 longs also avoids adjacent-line hardware prefetcher bouncing.

3.Zero Lock Hot Path: Achieves < 5 ns amortized increment and linear 16-core scaling.

4.perf c2c Verified: Eliminates cross-core HITM stalls in hardware performance counters.

Isolating each thread's counter on its own 64-byte (or 128-byte) cache line restores 800M+ ops/sec linear scaling.

import java.util.concurrent.atomic.LongAdder;

// Option 1: JDK standard striped & @Contended-padded counter
public final class TelemetryCounters {
    private final LongAdder events = new LongAdder();
    public void record() { events.increment(); }         // <5 ns, zero RFO bouncing
    public long snapshot() { return events.sum(); }    // called every 100ms
}

// Option 2: Fixed worker-ID array with 128-byte stride (no -XX:-RestrictContended needed)
public final class PaddedWorkerCounters {
    private static final int STRIDE = 16; // 16 * 8B = 128B (defeats spatial prefetcher)
    private final long[] slots;
    public PaddedWorkerCounters(int workers) { this.slots = new long[workers * STRIDE]; }
    public void inc(int workerId) { slots[workerId * STRIDE]++; }
    public long total(int workers) {
        long s = 0;
        for (int i = 0; i < workers; i++) s += slots[i * STRIDE];
        return s;
    }
}
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Cache-Line Padding applies in High-Throughput Systems.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Eliminating false sharing is a staple of low-latency infrastructure:

  • LMAX Disruptor Ring Buffer: Padding Sequence cursors (p1..p7) so producer and consumer heads never share a cache line.
  • Metrics & Observability Agents: LongAdder / Striped64 powering Micrometer, Prometheus, and Netty byte counters.
  • HFT & Telemetry Pipelines: Per-core statistics arrays padded to 64/128 bytes.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does incrementing distinct indices of a shared long[8] array across 8 CPU cores collapse throughput?

Recommended Learning Flow