Disruptor - Ring Buffer
Asked Answered
W

1

5

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
{
....
Wiley answered 12/8, 2015 at 13:34 Comment(1)
It has to do with false sharing see: https://mcmap.net/q/851516/-efficiency-of-multithreaded-loops en.wikipedia.org/wiki/False_sharingWound
H
8

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.

Hinge answered 12/8, 2015 at 13:38 Comment(7)
False sharing did not come to mind, actually the LMAX's white paper mentioned about cache line, after seeing your answer I remembered it, but seems I did not took it seriously, anyway thank you for directing me to right placeWiley
I found very useful post on False Sharing by Martin Thompson (Mechanical Sympathy) mechanical-sympathy.blogspot.kr/2011/07/false-sharing.htmlWiley
Which long value is actually used in the Ring Buffer class and has the potential to be falsely shared? From my understanding Sequencer is the class containing the long that has the potential to be falsely shared.Cavil
@Cavil if you create two RingBuffers they could use the same cache line without padding.Hinge
@PeterLawrey Agreed. But which part of the ring buffer state is padded to avoid False sharing. Isn't the object array already padded with BUFFER_PAD on both sides along with the sequencer? I am not a Java programmer so I might be missing something fundamental here. Thank you.Cavil
@Cavil arrays are objects and are not part of the encoding object. In theory they could be anywhere else in memory.Hinge
@PeterLawrey I dont get the heading part, the cache line is 64 bytes. The value is both left-padded and right-padded with 7 long, leaving 4-bytes space. Why doesnt it padded one-more long to make it 64-bytes? I think I might miss some fundamental thing here but sorry for being stupid.Highfalutin

© 2022 - 2024 — McMap. All rights reserved.