而且有些实现类。
ByteArrayBuffer其实是对byte[]的封装,ByteBufferBuffer是对原始ByteBuffer的封装。LinkedBuffer是对buffer数组的封装,他们都有个wrap方法。Delegate开头的都是这些buffer代理类,
如果使用的ByteArrayEncoder,ByteBufferEncoder,BufferEncoder这些来编码的话, 选择具体哪个buffer是在BufferFactory类确定的,如
public static Buffer wrap(byte[] array) { return ByteArrayBuffer.wrap(array); }
如果使用的是SerialEncoder来编码的话,buffer的构建是由BufferBuilder。
public BufferBuilder(int capacity) { if (capacity <= 0) capacity = 512; buffer = BufferFactory.allocate(capacity); }
BufferPool的实现类有DefaultBufferPool和NullBufferPool
DefaultBufferPool:
public static Buffer allocate(int capacity, boolean direct) { if (capacity < 0) throw new IllegalArgumentException(); return pool.allocate(capacity, direct); }
public Buffer allocate(int capacity, boolean direct) { getCount.incrementAndGet(); int index = indexFor(capacity); if (index >= 0) { Integer key = new Integer(capacity); Object obj = get(direct, index, key); if (obj == null && ++index != POSITIVE_INTEGER_SIZE) obj = get(direct, index, key); if (obj != null) { hitCount.incrementAndGet(); if (direct) { ByteBuffer content = (ByteBuffer) obj; content.clear(); return new DirectBuffer(content, capacity); } else { return new HeapBuffer((byte[]) obj, capacity); }
可以看到DefaultBufferPool最后得到的要么是DirectBuffer,要么是HeapBuffer。
BufferFactory:
private static final boolean useDirectBuffer = Configuration .isUseDirectBuffer();
除非配置文件写了使用DirectBuffer,否则使用的是HeapBuffer
NullBufferPool :
public class NullBufferPool implements BufferPool { public Buffer allocate(int capacity, boolean direct) { return direct ? (Buffer) ByteBufferBuffer.allocate(capacity, true) : ByteArrayBuffer.allocate(capacity); } }
NullBufferPool 得到是ByteBufferBuffer。
当buffer的资源释放异常的时候会 抛出ReleasedBufferException这个异常。
总的来说buffer的结构还是比较清晰的,就是看起来好像类很多。