Backend Development 12 min read

Understanding Java Disruptor: Queues, Core Components, and High‑Performance Lock‑Free Design

This article introduces various Java queue implementations, explains the Disruptor framework’s architecture, demonstrates its usage with complete code examples, and analyzes core components such as RingBuffer, Sequencer, and WaitStrategy while addressing performance issues like false sharing and multi‑producer coordination.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Understanding Java Disruptor: Queues, Core Components, and High‑Performance Lock‑Free Design

Java Queue Implementations

ArrayBlockingQueue – uses ReentrantLock

LinkedBlockingQueue – uses ReentrantLock

ConcurrentLinkedQueue – uses CAS

etc.

Locks have relatively low performance, so lock‑free designs are preferred. Next we explore the Disruptor framework.

Disruptor Simple Usage

GitHub repository: https://github.com/LMAX-Exchange/disruptor/wiki/Performance-Results

Disruptor is an open‑source concurrent framework that won the 2011 Duke’s Choice Award; it provides a lock‑free network queue implementation. It was developed by LMAX, a UK foreign‑exchange trading company, and can handle up to 6 million orders per second on a single thread.

Log4j2 asynchronous mode uses Disruptor for event handling.

Limitation: it is an in‑memory queue and cannot be used in distributed scenarios.

Code Example – Data Transfer Object

@Data
public class EventData {
    private Long value;
}

Code Example – Consumer

public class EventConsumer implements WorkHandler
{
    /**
     * Consumer callback
     * @param eventData
     * @throws Exception
     */
    @Override
    public void onEvent(EventData eventData) throws Exception {
        Thread.sleep(5000);
        System.out.println(Thread.currentThread() + ", eventData:" + eventData.getValue());
    }
}

Code Example – Producer

public class EventProducer {
    private final RingBuffer
ringBuffer;

    public EventProducer(RingBuffer
ringBuffer) {
        this.ringBuffer = ringBuffer;
    }

    public void sendData(Long v) {
        // CAS slot reservation
        long next = ringBuffer.next();
        try {
            EventData eventData = ringBuffer.get(next);
            eventData.setValue(v);
        } finally {
            System.out.println("EventProducer send success, sequence:" + next);
            ringBuffer.publish(next);
        }
    }
}

Code Example – Test Class

public class DisruptorTest {
    public static void main(String[] args) {
        int bufferSize = 8; // power of two
        Disruptor
disruptor = new Disruptor<>(
                EventData::new, // event factory
                bufferSize,
                Executors.defaultThreadFactory(),
                ProducerType.MULTI,
                new BlockingWaitStrategy());
        // configure consumers
        disruptor.handleEventsWithWorkerPool(
                new EventConsumer(), new EventConsumer(), new EventConsumer(), new EventConsumer());
        disruptor.start();
        RingBuffer
ringBuffer = disruptor.getRingBuffer();
        EventProducer eventProducer = new EventProducer(ringBuffer);
        long i = 0;
        for (;;) {
            i++;
            eventProducer.sendData(i);
            try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); }
        }
    }
}

Core Components of Disruptor

RingBuffer : a circular array that pre‑allocates entries to avoid object allocation during runtime; updates occur in‑place.

Sequencer : the central coordinator. Implementations include SingleProducerSequencer and MultiProducerSequencer . It tracks the current write cursor, the minimum consumer sequence, and the array Sequence[] gatingSequences .

Sequence : essentially an atomic integer that records progress; padded to avoid false sharing.

WorkProcessor : loops to fetch events from the Disruptor and dispatches them to registered handlers.

EventHandler : user‑implemented business‑logic handler.

WaitStrategy : defines how consumers wait for events. Options include: SleepingWaitStrategy : spin → yield → sleep BlockingWaitStrategy : lock‑based, suitable when CPU resources are scarce YieldingWaitStrategy : spin → yield → spin BusySpinWaitStrategy : pure spin, minimizes context switches PhasedBackoffWaitStrategy : spin → yield → custom

Analyzing the Code with Questions

1. How does a multi‑producer ensure that messages are not overwritten? Each thread reserves a distinct segment of the ring buffer using CAS; if the segment is already taken, the thread spins or parks until space becomes available.

2. How does the Sequencer know which slots are safe to write when some are still being consumed? It obtains the minimum sequence among all consumers ( gatingSequences ) and only allows producers to claim slots up to minConsumerSequence + bufferSize - 1 .

3. In a multi‑producer scenario, how do consumers know which sequences are ready to be consumed? After a producer publishes an event, it marks the corresponding entry in availableBuffer as 1. Consumers read the highest published sequence via getHighestPublishedSequence , which scans availableBuffer for the first unavailable slot.

Solving False Sharing

CPU caches operate on cache lines (typically 64 bytes). When multiple threads modify variables that share the same cache line, they cause cache‑line invalidation, known as false sharing. Disruptor mitigates this by padding critical fields (e.g., adding seven long values before and after a sequence) so each frequently updated variable occupies its own cache line.

Review – Why Disruptor Is a High‑Performance Lock‑Free Queue

Cache‑line padding eliminates false sharing (Java 8 provides @sun.misc.Contended for the same purpose).

Lock‑free coordination via CAS (two‑phase commit).

Circular array design avoids garbage‑collection pressure.

Heavy use of bit‑wise operations for fast index calculations.

Source: blog.csdn.net/wd904396578/article/details/126249002
JavaPerformanceDisruptorfalse sharinglock-freeringbufferConcurrent Queue
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.