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

Lock-Free Ring Buffer
(LMAX Disruptor).

Standard BlockingQueues suffer mutex contention, kernel futex wakeups, GC node allocations, and L1 false sharing.
Start the journey3 sections
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

Pre-allocate a power-of-2 Object[] ring, pad writeCursor and readCursor to 64-byte cache lines, and guard each slot with an AtomicLong sequence counter.

TL;DR30-second simplified summary
▾

Power-of-2 bitmasking (seq & (N-1)) + 64B cache-line padding + per-slot publishedSeq delivers 10M+ ops/sec with sub-microsecond p99.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
64-Byte CPU Cache Lines & MESI
Adjacent atomics on the same 64B line trigger cross-core invalidation storms (false sharing).
Compare-And-Swap (CAS)
Lock-free atomic read-modify-write CPU instruction (LOCK CMPXCHG).
Full walkthrough · 3 stages
01
L4 · FUNDAMENTALS

P — Why LinkedBlockingQueue Stalls at 10M Ops/Sec.

BlockingQueue vs. Lock-Free Ring Buffer

Before · LinkedBlockingQueue
After · Padded MPMC Ring Buffer

Every LinkedBlockingQueue.offer() allocates a heap Node (triggering GC pauses) and acquires a ReentrantLock (triggering kernel futex context switches). Even lock-free linked queues suffer cache misses chasing pointers and false sharing when head and tail share a 64-byte cache line.

02
L4 · FUNDAMENTALS

R & I — Per-Slot Sequence Barrier in Java.

Power-of-2 Ring Buffer with Sequence Cursors

1. Hash Ring, Clockwise Lookup & Replication
clockwise[0 .. 2³² − 1]hash(key) → ringSlot 0 (seq=N)Slot 1 (seq=N+1)Slot 2 (Write)Slot 3 (Read)PrimaryReplica (next physical)
2. Virtual Nodes (Even Arc Distribution)
Vnodes / Server150–256 tokens eachS1#0S2#0S3#0S1#1S2#1S3#1S1#2S2#2
Engineering Decision Framework
Problem
How do you pass 10M+ events/sec between threads with < 1 us p99 latency?
Naive Solution
Use java.util.concurrent.ArrayBlockingQueue or LinkedBlockingQueue.
Why It Fails
Mutex contention, kernel futex sleep/wake, and GC pressure blow the 1 us budget.
Alternatives
Cache-line padded MPMC Ring Buffer,ArrayBlockingQueue (mutex),ConcurrentLinkedQueue (GC nodes)
Engineering Decision
Use a pre-allocated power-of-2 Ring Buffer with 64-byte padded cursors and per-slot sequence barriers.
Trade-Offs
Fixed bounded capacity and busy-spin CPU usage under load, but zero GC and sub-microsecond latency.
Decision Exercise · Make the Call

Why must the ring buffer capacity be a power of 2 (e.g., 1024, 65536)?

In an MPMC ring of size N = 2^k, two threads can wrap around to the same physical index pos & (N-1). A per-slot AtomicLong publishedSeq[i] (initialized to i) ensures producers only write when publishedSeq[idx] == pos and consumers only read when publishedSeq[idx] == pos + 1:

import java.util.concurrent.atomic.AtomicLong;

public final class MpmcRingBuffer<T> {
    private final int mask;
    private final Object[] slots;
    private final AtomicLong[] publishedSeq;
    private long p1, p2, p3, p4, p5, p6, p7; // 64B padding
    private final AtomicLong writeCursor = new AtomicLong(0);
    private long q1, q2, q3, q4, q5, q6, q7;
    private final AtomicLong readCursor = new AtomicLong(0);

    public MpmcRingBuffer(int capPow2) {
        this.mask = capPow2 - 1;
        this.slots = new Object[capPow2];
        this.publishedSeq = new AtomicLong[capPow2];
        for (int i = 0; i < capPow2; i++) publishedSeq[i] = new AtomicLong(i);
    }

    public boolean tryOffer(T item) {
        while (true) {
            long pos = writeCursor.get();
            int idx = (int) (pos & mask);
            long diff = publishedSeq[idx].get() - pos;
            if (diff == 0 && writeCursor.compareAndSet(pos, pos + 1)) {
                slots[idx] = item;
                publishedSeq[idx].lazySet(pos + 1);
                return true;
            } else if (diff < 0) return false;
        }
    }
}
03
L5 · APPLIED DESIGN

M & E — Wait Strategies & When Not to Use Ring Buffers.

Slot Sequence Lifecycle

CAS writeCursorlazySet(pos+1)Consumer lazySet(pos+N)SEQ == POS (FREE)CLAIMED_BY_PRODUC…SEQ == POS+1(READY)

Producers/consumers choose a wait strategy: BusySpin (lowest latency, 100% CPU core), Yielding (Thread.onSpinWait() + yield()), or Sleeping. When NOT to use a Ring Buffer: Variable-length unbounded workloads (e.g., unpredictable webhook bursts) where fixed pre-allocated slots either OOM or drop messages.

Recommended Learning Flow