//polyglot programmer /
Publishing to the Disruptor
Writing to the RingBuffer is achieved
using a two-phase commit. First, Stage 1
(the Publisher) has to determine the next
available slot in the RingBuffer, as shown
in Figure 3.
The RingBuffer has the sequence num-
ber of the most recently written-to slot
(Slot 18 in Figure 3) and, therefore, it can
determine the next sequence number
and, consequently, the corresponding
slot in the array.
RingBuffer for you, but I’m going
to outline how that works to
highlight the design.
While the Publisher needed to
ask the RingBuffer for the number of the next slot to write to, an
EventProcessor, which is kind of
like a consumer except it doesn’t
actually consume (remove)
things from the RingBuffer, will
track the last sequence number
it processed and ask for the next
sequence number it wants.
Figure 6 shows the
EventProcessor waiting for
the next expected sequence
number.
Rather than asking
the RingBuffer directly
for its sequence number, an EventProcessor has a
SequenceBarrier do this job. This
detail is not important for the
case we’re looking at now, but its
purpose will become apparent later.
In Figure 6, Stage 2, the EventProcessor
has seen up to sequence number 16. It
wants the item at Slot 17 next, so it calls
waitFor( 17) on the SequenceBarrier. Stage
2 can happily hang around waiting for
the next sequence number, because it
might be that nothing else has written to
the RingBuffer. If so, there’s nothing else
to process. However, in the case shown in
Figure 6, the RingBuffer has been populated up to Slot 18, so waitFor returns the
number 18, telling the EventProcessor
it can safely read anything up to and
including Slot 18, as shown in Figure 7.
This methodology provides some really
Figure 7
nice batching behavior, which you can
see in the BatchEventProcessor code. The
code simply asks the RingBuffer for every
item from the next value it needs up to
the highest available sequence number.
You can use this batching code by
implementing EventHandler. There are
examples of how to use batching in the
Disruptor performance tests, for example FizzBuzzEventHandler.
blog
Figure 5
Reading from the RingBuffer
The Disruptor framework
includes a BatchEventProcessor
that will read events from the
Is It a Low-Latency Queue?
Sure, it can be used as such. We have
figures from testing early versions of the
Disruptor that show how much faster it
is than ArrayBlockingQueue for a three-