Backend Development 12 min read

Comprehensive Guide to Disruptor: Core Concepts, Implementation, and Demo in Java

This article introduces the high‑performance Disruptor library, explains its background, core concepts such as RingBuffer, Sequence, Sequencer, and WaitStrategy, and provides a step‑by‑step Java implementation with Maven dependencies, event factories, handlers, producers, and a runnable test case.

Top Architect
Top Architect
Top Architect
Comprehensive Guide to Disruptor: Core Concepts, Implementation, and Demo in Java

01、Background

In a recent project the author needed a fast in‑memory message queue and chose LMAX Disruptor instead of Kafka or RabbitMQ because of its extreme speed and open‑source nature.

02、Disruptor Introduction

Disruptor is a high‑performance Java library originally developed by LMAX Exchange to solve latency issues of traditional memory queues; a single‑threaded implementation can handle up to 6 million orders per second. It is designed for the producer‑consumer problem, providing a bounded, lock‑free queue with very low latency.

03、Core Concepts

The essential domain objects of Disruptor are RingBuffer, Sequence, Sequencer, SequenceBarrier, WaitStrategy, Event, EventProcessor, EventHandler, and Producer.

04、Ring Buffer

The RingBuffer stores events in a circular array; since version 3.0 its responsibility is limited to storing and updating events, and users can replace it with a custom implementation if needed.

05、Sequence Disruptor

Sequence numbers are used to order events and track the progress of each consumer, avoiding false sharing between CPU caches.

06、Sequencer

The Sequencer is the core interface with two implementations – SingleProducerSequencer and MultiProducerSequencer – that manage the fast, correct hand‑off of data between producers and consumers.

07、Sequence Barrier

SequenceBarrier keeps references to the main published sequence of the RingBuffer and the dependent consumers, determining whether a consumer can process more events.

08、Wait Strategy

WaitStrategy defines how a consumer waits for the next event; Disruptor provides several strategies with different performance characteristics.

09、Event

An Event is the data exchanged between producer and consumer; its type is defined by the user.

10、EventProcessor

EventProcessor holds a consumer’s Sequence and runs the event loop that invokes the consumer’s handling logic.

11、EventHandler

EventHandler is a user‑implemented interface that processes each Event.

12、Producer

The Producer is any user code that publishes events to the Disruptor; the framework does not define a specific interface for it.

13、Demo

The following steps show a complete working example:

Add Maven dependency:

<dependency>
    <groupId>com.lmax</groupId>
    <artifactId>disruptor</artifactId>
    <version>3.3.4</version>
</dependency>

Create the message model:

@Data
public class MessageModel {
    private String message;
}

Implement EventFactory:

public class HelloEventFactory implements EventFactory
{
    @Override
    public MessageModel newInstance() {
        return new MessageModel();
    }
}

Implement EventHandler (consumer):

@Slf4j
public class HelloEventHandler implements EventHandler
{
    @Override
    public void onEvent(MessageModel event, long sequence, boolean endOfBatch) {
        try {
            Thread.sleep(1000);
            log.info("消费者处理消息开始");
            if (event != null) {
                log.info("消费者消费的信息是:{}", event);
            }
        } catch (Exception e) {
            log.info("消费者处理消息失败");
        }
        log.info("消费者处理消息结束");
    }
}

Configure RingBuffer bean:

@Configuration
public class MQManager {
    @Bean("messageModel")
    public RingBuffer
messageModelRingBuffer() {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        HelloEventFactory factory = new HelloEventFactory();
        int bufferSize = 1024 * 256;
        Disruptor
disruptor = new Disruptor<>(factory, bufferSize, executor,
                ProducerType.SINGLE, new BlockingWaitStrategy());
        disruptor.handleEventsWith(new HelloEventHandler());
        disruptor.start();
        return disruptor.getRingBuffer();
    }
}

Define service interface and implementation (producer):

public interface DisruptorMqService {
    void sayHelloMq(String message);
}

@Slf4j
@Component
@Service
public class DisruptorMqServiceImpl implements DisruptorMqService {
    @Autowired
    private RingBuffer
messageModelRingBuffer;

    @Override
    public void sayHelloMq(String message) {
        log.info("record the message: {}", message);
        long sequence = messageModelRingBuffer.next();
        try {
            MessageModel event = messageModelRingBuffer.get(sequence);
            event.setMessage(message);
            log.info("往消息队列中添加消息:{}", event);
        } catch (Exception e) {
            log.error("failed to add event", e);
        } finally {
            messageModelRingBuffer.publish(sequence);
        }
    }
}

Create a SpringBoot test class:

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class DemoApplicationTests {
    @Autowired
    private DisruptorMqService disruptorMqService;

    @Test
    public void sayHelloMqTest() throws Exception {
        disruptorMqService.sayHelloMq("消息到了,Hello world!");
        log.info("消息队列已发送完毕");
        Thread.sleep(2000);
    }
}

The test output shows the producer logging the message, the consumer starting, processing, and finishing, confirming the asynchronous, lock‑free behavior of Disruptor.

14、Conclusion

The producer‑consumer pattern is common, but Disruptor implements it entirely in memory without locks, which explains its high efficiency.

backendJavaConcurrencyDisruptorHighPerformanceMessageQueueringbuffer
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

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.