Search code examples
javadata-structurescircular-bufferdisruptor-pattern

Disruptor - Ring Buffer


I am investigating LMAX Disruptor's source code, and I came into RingBuffer abstract class. Why are there exactly 7 long fields (p1 ... p7) in RingBufferPad ? Here is actual code : https://github.com/LMAX-Exchange/disruptor/blob/master/src/main/java/com/lmax/disruptor/RingBuffer.java

abstract class RingBufferPad
{
    protected long p1, p2, p3, p4, p5, p6, p7;
}

abstract class RingBufferFields<E> extends RingBufferPad
{
....

Solution

  • This is to ensure the long value which is actually used is on it's own cache line. This avoid false sharing where you have two longs which need to be updated by different threads competing for the same cache line.

    The assumption here is that the CPU cache line length is 64 bytes (and it is on most architectures e.g. ARM, AMD and Intel CPUs). Using 7 longs is slightly paranoid as the header will be 8 bytes min, 16 bytes max (with allocation alignment) so 6 or even 5 long values would be enough.