Disruptor源码(二)填充缓存行消除伪共享

缓存行

  • CPU缓存是以缓存行为单位存储的;
  • 缓存行是2的整数幂个连续字节,一般为32-256个字节;
  • 最常见的缓存行大小是64字节;

伪共享

  • 当多个线程修改相互独立的变量时,如果这些变量共享同一个缓存行,就是伪共享;

消除伪共享

  • 让变量变胖,自己一个人就占满缓存行;

Sequence消除缓存行的实现

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

class Value extends LhsPadding
{
    protected volatile long value;
}

class RhsPadding extends Value
{
    protected long p9, p10, p11, p12, p13, p14, p15;
}

public class Sequence extends RhsPadding
{
    static final long INITIAL_VALUE = -1L;
    private static final Unsafe UNSAFE;
    private static final long VALUE_OFFSET;

    static
    {
        UNSAFE = Util.getUnsafe();
        try
        {
            VALUE_OFFSET = UNSAFE.objectFieldOffset(Value.class.getDeclaredField("value"));
        }
        catch (final Exception e)
        {
            throw new RuntimeException(e);
        }
    }

}

你可能感兴趣的:(Disruptor源码(二)填充缓存行消除伪共享)