RingBuffer,从字面上看,它是一个环形缓冲队列。实际上,它不是一个队列,因为它不具备队列的特性,比如FIFO等。
RingBuffer本身是一个数组,之所以说它是环形队列,因为它通过算法维持了一个类似环形队列的数据结构。
上图是对RingBuffer的一个抽象描述。
假定一个8个槽的RingBuffer,则本质上是一个长度为8的数组,那如何模拟一个环形队列呢?
通过序列号(sequence)来映射数据元素在数组中的下标。Sequence是一个从0开始,一直递增的序列号,其映射关系为:index = sequence & (array length-1)。
RingBufferPad和RingBufferFields源码如下:
abstract class RingBufferPad
{
protected long p1, p2, p3, p4, p5, p6, p7;
}
abstract class RingBufferFields<E> extends RingBufferPad
{
private static final int BUFFER_PAD;
private static final long REF_ARRAY_BASE;
private static final int REF_ELEMENT_SHIFT;
private static final Unsafe UNSAFE = Util.getUnsafe();
static
{
final int scale = UNSAFE.arrayIndexScale(Object[].class);
if (4 == scale)
{
REF_ELEMENT_SHIFT = 2;
}
else if (8 == scale)
{
REF_ELEMENT_SHIFT = 3;
}
else
{
throw new IllegalStateException("Unknown pointer size");
}
BUFFER_PAD = 128 / scale;
// Including the buffer pad in the array base offset
REF_ARRAY_BASE = UNSAFE.arrayBaseOffset(Object[].class) + 128;
}
private final long indexMask;
private final Object[] entries;
protected final int bufferSize;
protected final Sequencer sequencer;
RingBufferFields(
EventFactory<E> eventFactory,
Sequencer sequencer)
{
this.sequencer = sequencer;
this.bufferSize = sequencer.getBufferSize();
if (bufferSize < 1)
{
throw new IllegalArgumentException("bufferSize must not be less than 1");
}
if (Integer.bitCount(bufferSize) != 1)
{
throw new IllegalArgumentException("bufferSize must be a po