Search code examples
javadisruptor-pattern

Do class fields within an LMAX Disruptor event need to be volatile?


Sample code from the LMAX Disruptor "Getting Started"...

public class LongEvent
{
    private long value;

    public void set(long value)
    {
        this.value = value;
    }
}

Ref: https://github.com/LMAX-Exchange/disruptor/wiki/Getting-Started

Why isn't private long value declared as volatile?

I ask because, implicit to the Disruptor pattern, data is shared between threads (producer -> consumer).

My guess: There is already (at least) one memory fence between the producer and consumer threads.


Solution

  • Peter's comment gives a good clue, and in fact, yes there are memory fences involved.

    You can see a putOrderedLong() compareAndSet() and so on are used in the Sequence class. Each of these enforce memory ordering.

    See the source code for more details.