StackPractices
advanced By Mathias Paulenko

Lock-Free Queue Pattern

Build high-throughput queues using atomic operations instead of locks. Multiple threads can enqueue and dequeue concurrently without blocking or context-switching overhead.

Overview

A lock-based queue makes every thread wait in line for a mutex. Under contention that turns into two real problems: blocked threads burn CPU scheduler time, and a low-priority thread holding the lock can stall a high-priority one (priority inversion).

Lock-free queues drop the lock entirely. Threads update head and tail pointers with atomic operations, usually compare-and-swap (CAS), and if a CAS loses the race, the thread just retries. Nobody blocks. This pattern is the standard fix for hot producer-consumer paths; if that’s your shape, the producer-consumer pattern is the broader design this plugs into.

When to Use

  • Two or more threads enqueue and dequeue at high frequency
  • Lock contention shows up in profiling as throughput loss or latency spikes
  • You need predictable latency: no blocking, no context-switch storms
  • You’re building messaging, event dispatch, or work-stealing internals

Skip it when contention is low (a Mutex<Queue> is simpler and just as fast), when you need blocking semantics like “wait until an item arrives” (ArrayBlockingQueue already does that well), or when you’re tempted to write a general MPMC queue by hand: that’s a research-grade problem; use a battle-tested library.

Solution

Python: SPSC ring buffer

For a single producer and a single consumer you don’t need CAS at all. Each thread owns exactly one index (the producer writes head, the consumer writes tail), so there’s no shared variable to race on.

import threading
import time
import random

class SpscRingBuffer:
    """Single-producer, single-consumer lock-free ring buffer.
    Producer owns `head`, consumer owns `tail`. One slot is left
    empty so 'full' and 'empty' are distinguishable."""

    def __init__(self, capacity):
        self.capacity = capacity
        self.buffer = [None] * capacity
        self.head = 0  # write index — producer only
        self.tail = 0  # read index — consumer only

    def enqueue(self, item):
        next_head = (self.head + 1) % self.capacity
        while next_head == self.tail:
            pass  # buffer full — spin
        self.buffer[self.head] = item
        self.head = next_head  # publish AFTER writing the data

    def dequeue(self):
        while self.tail == self.head:
            pass  # buffer empty — spin
        item = self.buffer[self.tail]
        self.buffer[self.tail] = None
        self.tail = (self.tail + 1) % self.capacity
        return item

buffer = SpscRingBuffer(100)

def producer(count):
    for i in range(count):
        buffer.enqueue(f"item-{i}")
        time.sleep(random.uniform(0, 0.001))

def consumer(count):
    processed = 0
    for _ in range(count):
        item = buffer.dequeue()
        processed += 1
        if processed % 1000 == 0:
            print(f"Processed {processed} items, last: {item}")

p = threading.Thread(target=producer, args=(10000,))
c = threading.Thread(target=consumer, args=(10000,))
p.start(); c.start()
p.join(); c.join()
print("All done")

One caveat: this works in CPython because the GIL makes single-attribute reads and writes atomic in practice, and the protocol only needs that. In C++, Rust, or any weak-memory-model target you’d publish the index with release ordering and read the other index with acquire ordering. See the Advanced Techniques section.

JavaScript: Atomics + SharedArrayBuffer

Same SPSC idea, but safe to share across worker_threads via SharedArrayBuffer. Atomics operations are sequentially consistent, so no extra fences are needed. Here head and tail grow unbounded and wrap with % capacity, which lets you use every slot:

import { Worker, isMainThread, parentPort, workerData } from "worker_threads";

class SpscRingBuffer {
  constructor(capacity) {
    this.capacity = capacity;
    this.buffer = new SharedArrayBuffer(capacity * 4 + 8);
    this.data = new Int32Array(this.buffer, 0, capacity);
    this.indices = new Int32Array(this.buffer, capacity * 4, 2);
    // indices[0] = head (write), indices[1] = tail (read)
  }
}

if (isMainThread) {
  const ring = new SpscRingBuffer(1000);
  for (const role of ["producer", "consumer"]) {
    const w = new Worker(new URL(import.meta.url), {
      workerData: { role, buffer: ring.buffer, capacity: ring.capacity },
    });
    w.on("message", (msg) => console.log(msg));
  }
} else {
  const { role, buffer, capacity } = workerData;
  const data = new Int32Array(buffer, 0, capacity);
  const indices = new Int32Array(buffer, capacity * 4, 2);

  if (role === "producer") {
    for (let i = 0; i < 10000; i++) {
      let head = Atomics.load(indices, 0);
      while (head - Atomics.load(indices, 1) >= capacity) {}
      Atomics.store(data, head % capacity, i);
      Atomics.store(indices, 0, head + 1); // publish after writing
    }
    parentPort.postMessage("Producer done: 10000 items");
  } else {
    for (let i = 0; i < 10000; i++) {
      let tail = Atomics.load(indices, 1);
      while (tail >= Atomics.load(indices, 0)) {}
      Atomics.load(data, tail % capacity);
      Atomics.store(indices, 1, tail + 1);
    }
    parentPort.postMessage("Consumer done: 10000 items");
  }
}

Java: ConcurrentLinkedQueue

For MPMC you almost never write your own. ConcurrentLinkedQueue is the Michael & Scott algorithm, CAS on node pointers in a linked list, and it’s lock-free, unbounded, and already correct:

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class LockFreeQueueExample {

    public static void main(String[] args) throws InterruptedException {
        ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>();
        AtomicInteger produced = new AtomicInteger();
        AtomicInteger consumed = new AtomicInteger();

        Runnable producer = () -> {
            for (int i = 0; i < 10000; i++) {
                queue.offer(i);
                produced.incrementAndGet();
            }
        };
        Runnable consumer = () -> {
            while (consumed.get() < 20000) {
                if (queue.poll() != null) consumed.incrementAndGet();
            }
        };

        ExecutorService pool = Executors.newFixedThreadPool(4);
        pool.submit(producer);
        pool.submit(producer); // 2 producers → 20k items total
        pool.submit(consumer);
        pool.submit(consumer); // 2 consumers
        pool.shutdown();
        pool.awaitTermination(10, TimeUnit.SECONDS);
        System.out.println("Produced: " + produced + ", Consumed: " + consumed);
    }
}

Explanation

The mechanism depends on the variant. For MPMC linked-list queues like Michael & Scott, enqueue reads the current tail, links the new node after it, then CASes the tail pointer forward. If another thread got there first, the CAS fails and the thread retries with the fresh tail:

CAS enqueue loop: read tail, link node, try CAS on tail pointer, retry on failure

The key guarantee is system-wide progress: some thread always makes progress, even if individual threads retry. Under low contention CAS succeeds on the first try; under high contention threads retry a few times, but retrying is still cheaper than a context switch.

For ring buffers the trick is different: ownership, not retries. The producer is the only writer of head, the consumer the only writer of tail. Each side reads the other’s index to detect full or empty, and the slot itself is written before the index that publishes it. That ordering is the whole correctness argument.

Common algorithms:

  • Michael & Scott: unbounded linked-list queue, the one inside ConcurrentLinkedQueue.
  • SPSC ring buffer: circular buffer, no CAS at all. Lowest possible overhead.
  • MPMC ring buffer (Vyukov): bounded circular buffer with per-slot sequence numbers; CAS on head/tail.
  • Disruptor: ring buffer plus consumer barriers; what LMAX built for trading.

Variants

VariantProducers/ConsumersSynchronizationUse caseTradeoff
SPSC Ring Buffer1 / 1Index ownership onlyLowest latencyOne producer, one consumer
MPMC Ring BufferN / NCAS on head + tailGeneral purposeCAS contention under load
Michael & ScottN / NCAS on linked listUnboundedAllocation per node
DisruptorN / NSequences + barriersUltra-low latencyComplex, fixed size
SkipList QueueN / NCAS on skip listPriority orderingHigher overhead

What Works

  • Prefer an SPSC ring buffer when the topology allows it: zero CAS, zero contention.
  • Use ConcurrentLinkedQueue (Java), crossbeam::queue (Rust), or Atomics (JS) instead of hand-rolling MPMC.
  • Pre-allocate the ring buffer; allocation inside the hot loop kills latency.
  • Pad head and tail onto separate cache lines (see false sharing below.
  • Measure CAS retry rate. If it’s high, shard: one queue per producer, then merge.
  • Size the buffer to absorb your burst. Too small means producers spin; spinning wastes CPU.
  • If you truly need sub-microsecond latency, look at the Disruptor instead.

Common Mistakes

  • Reaching for lock-free when a mutex would do. At moderate contention a lock-based queue is simpler and just as fast. Lock-free buys you predictability, not magic throughput.
  • Sharing a counter between producer and consumer. count += 1 / count -= 1 on a shared variable is a race even in CPython. Separate head and tail ownership is what makes SPSC work.
  • Publishing the index before writing the data. head = next must come after buffer[head] = item, or the consumer reads a slot that was never written. Memory ordering exists to make this guarantee portable.
  • The ABA problem. A thread reads A, another flips it to B and back to A, and the CAS succeeds but the structure changed in between. Linked-list queues need tagged pointers or epoch reclamation; it’s why M&S implementations version their pointers.
  • Unbounded spinning. A permanently full or empty queue burns a core. Add backoff or yield, or fall back to a blocking wait.
  • Ignoring false sharing. If head and tail share a cache line, every update invalidates the other thread’s cache. Pad to 64 bytes.
  • Assuming lock-free means wait-free. Lock-free guarantees some thread progresses; an unlucky one can starve. Wait-free bounds every thread’s steps but costs more.

Advanced Techniques

Avoiding false sharing with cache-line padding

head and tail live on the same cache line by default. Every store to one invalidates the line for the other thread, so your “lock-free” queue spends its time on cache coherence traffic. Force them apart:

struct alignas(64) PaddedAtomic {
    std::atomic<size_t> value;
    // remaining bytes of the 64-byte line are padding
};

PaddedAtomic head;
PaddedAtomic tail;

alignas(64) puts each index at the start of its own cache line. In Rust, crates like crossbeam-utils provide CachePadded for exactly this.

Acquire/release ordering on weak memory models

x86 will mostly paper over missing fences; ARM and POWER won’t. The portable rule: the producer release-stores the index after writing data, the consumer acquire-loads it before reading data.

// Producer — publish the slot with release ordering
buffer[idx] = value;
head.store(idx + 1, std::memory_order_release);

// Consumer — pair it with an acquire load
size_t h = head.load(std::memory_order_acquire);
if (tail < h) value = buffer[tail];

The release/acquire pair creates a happens-before edge: everything written before the release-store is visible after the acquire-load sees the new value.

MPMC in Rust: use crossbeam, don’t hand-roll

A correct bounded MPMC queue needs a sequence number per slot so a consumer can’t read a slot a producer claimed but hasn’t written yet. That’s Dmitry Vyukov’s algorithm, and easy to get subtly wrong. In practice you use crossbeam’s ArrayQueue, which is exactly that:

use crossbeam::queue::ArrayQueue;
use std::sync::Arc;
use std::thread;

fn main() {
    // Bounded MPMC lock-free queue, capacity 1024
    let queue = Arc::new(ArrayQueue::new(1024));
    let mut handles = vec![];

    for _ in 0..2 { // producers
        let q = Arc::clone(&queue);
        handles.push(thread::spawn(move || {
            for i in 0..5000usize {
                while q.push(i).is_err() {
                    std::hint::spin_loop(); // full — retry
                }
            }
        }));
    }
    for _ in 0..2 { // consumers
        let q = Arc::clone(&queue);
        handles.push(thread::spawn(move || {
            let mut taken = 0;
            while taken < 5000 {
                if q.pop().is_some() { taken += 1; }
            }
        }));
    }
    for h in handles { h.join().unwrap(); }
    println!("done");
}

push returns Err(item) when full so you can retry or drop; that’s your backpressure hook. If you need the raw algorithm instead of a dependency, read Vyukov’s bounded_mpmc_queue or the M&S paper linked below before writing your own.

Exponential backoff for spinning

Raw spinning burns a core when the queue stays full or empty. Back off exponentially and cap it:

def enqueue_with_backoff(self, item):
    backoff = 1
    while True:
        next_head = (self.head + 1) % self.capacity
        if next_head != self.tail:
            break
        time.sleep(backoff / 1000.0)
        backoff = min(backoff * 2, 100)  # cap at 100 ms
    self.buffer[self.head] = item
    self.head = next_head

For real production code, after the cap you’d escalate to threading.Event or futex rather than sleeping forever.

Batched enqueue: publish once for N items

Batching doesn’t need locks either. The producer accumulates items locally (nobody else can see them) and publishes the batch with a single head update. Using unbounded indices also lets the buffer use every slot:

class SpscRingBufferBatched:
    """Batched SPSC: producer builds a local batch, then publishes
    it with one head update. Still lock-free: nothing shared is
    mutated by more than one thread."""

    def __init__(self, capacity):
        self.capacity = capacity
        self.buffer = [None] * capacity
        self.head = 0  # unbounded — wrap with % capacity
        self.tail = 0

    def enqueue_batch(self, items):
        n = len(items)
        while self.head - self.tail + n > self.capacity:
            pass  # wait for room
        for i, item in enumerate(items):
            self.buffer[(self.head + i) % self.capacity] = item
        self.head += n  # single publish for the whole batch

    def dequeue_batch(self, max_items):
        n = min(self.head - self.tail, max_items)
        items = [self.buffer[(self.tail + i) % self.capacity]
                 for i in range(n)]
        self.tail += n
        return items

See Also

Frequently Asked Questions

What's the difference between lock-free and wait-free?

Lock-free means at least one thread always makes progress, though an unlucky thread can retry forever under contention. Wait-free bounds the number of steps for every thread. Wait-free is stronger but costs more to implement.

What is the ABA problem?

A thread reads value A, another changes it to B and back to A. The first thread's CAS succeeds even though the structure changed in between. Fixes: tagged pointers (a version counter next to the pointer), hazard pointers, or epoch-based reclamation.

When should I use a lock-free queue instead of a lock-based one?

When profiling shows lock overhead, blocking and context switches, dominating your throughput at high contention. At low contention a mutex-guarded queue is simpler and equally fast. Benchmark both before committing.

Is Java's ConcurrentLinkedQueue truly lock-free?

Yes. It's Michael & Scott with CAS on node pointers and never takes a lock. It's unbounded though: memory grows with queue size. For bounded queues use ArrayBlockingQueue (lock-based) or a ring buffer.

What is the Disruptor pattern?

LMAX's inter-thread messaging design: a pre-allocated ring buffer where producers claim sequence numbers and consumers track them via barriers, hitting sub-microsecond latency by eliminating locks, allocation, and false sharing, at the cost of real complexity.

How do I measure whether lock-free is worth it?

Benchmark lock-based vs lock-free under your actual contention level. Measure throughput (ops/sec), latency (p50/p99/p999), and CPU utilization. Lock-free typically wins at high contention and can lose at low contention because of CAS overhead.

Can lock-free queues starve threads?

Yes. Lock-free guarantees the system progresses, not that every thread does. A thread that keeps losing CAS races can starve. Wait-free algorithms bound per-thread steps but are harder to build. For most applications, lock-free is enough.

Do lock-free queues prevent priority inversion?

They sidestep it: with no lock to hold, a low-priority thread can't block a high-priority one. That's a genuine advantage in real-time systems: one of the few places lock-free is worth it almost by default.