PooledDirectByteBuf 基于内存池实现,与 UnpooledHeapByteBuf 的唯一不同就是内存的分配策略不同。
由于采用内存池实现,所以新创建 PooledDirectByteBuf 对象的时候不能直接 new 一个实力,而是从内存池中获取,然后设置引用计数器的值。它的具体代码如下:
static PooledDirectByteBuf newInstance(int maxCapacity) {
PooledDirectByteBuf buf = RECYCLER.get();
buf.reuse(maxCapacity);
return buf;
}
reuse 方法如下
final void reuse(int maxCapacity) {
maxCapacity(maxCapacity);
setRefCnt(1);
setIndex0(0, 0);
discardMarks();
}
它会直接从 Recycler<PooledDirectByteBuf>
池子中获取一个 PooledDirectByteBuf 对象,然后将它的引用计数器设置为 1,设置最大缓冲区容量,然后返回。
开发者如果想要复制一个新的实例,与原来的 PooledDirectByteBuf 保持独立,就可以调用 public ByteBuf copy(int index, int length)
方法,它的具体实现如下:
public ByteBuf copy(int index, int length) {
checkIndex(index, length);
ByteBuf copy = alloc().directBuffer(length, maxCapacity());
copy.writeBytes(this, index, length);
return copy;
}
本章我们了解了 Netty 的 PooledDirectByteBuf 源码,它是面向内存池的,和 UnpooledHeapByteBuf 操作基本相同,就只有内存分配策略不同。