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.
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.
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:
- Cache-Line Ownership Theft: Core 0 transitions the shared 64-byte line to
Modified, invalidating Core 1's copy. - HITM Stall Cycles: Core 1 stalls waiting to fetch the
Modifiedline (HITMinperf c2c) over the inter-core mesh. - Serialized Execution: Instead of 8× parallel speed, all 8 cores serialize on one cache line.
False Sharing on long[8] (1 Cache Line) vs. Padded Stripes
Padding each counter to >= 64 bytes (or using LongAdder) keeps each core's writes in its own L1 cache line.
- 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.
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?
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 longfields in the same object sit side-by-side in memory on the same 64-byte line. AtomicLongArray Density: ContiguousAtomicLongreferences/objects can still share cache lines, andAtomicLongCAS retries under contention.
Naive solution (and why AtomicLong[] or volatile fields still suffer)
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-paddedCellstripes hashed by thread probe; each thread increments its own 64-byte-isolatedCellin< 5 nsamortized, 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 to64bytes (stride of8longs =64bytes, or16longs =128bytes to defeat hardware spatial prefetchers) with zero JVM flags required. - Verification: Validate with JMH +
perf c2c(L1-dcache-load-missesandHITMdrop by> 95%).
Thread-Local L1 Cache Lines via LongAdder / 64B Stride
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;
}
}
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
Sequencecursors (p1..p7) so producer and consumer heads never share a cache line. - Metrics & Observability Agents:
LongAdder/Striped64powering Micrometer, Prometheus, and Netty byte counters. - HFT & Telemetry Pipelines: Per-core statistics arrays padded to 64/128 bytes.
Practice: Make the trade-off yourself.
Why does incrementing distinct indices of a shared long[8] array across 8 CPU cores collapse throughput?