目录
AbstractReferenceCountedByteBuf
NIO ByteBuffer局限性
- ByteBuffer长度固定,不能动态扩展和收缩。
- ByteBuffer只有一个position标识位置,读写需要flip()和rewind()来翻转,较难控制。
- API功能有限。
ByteBuf功能
基本功能
- 7种基础类型,byte数组,ByteBuffer(ByteBuf)等的读写
- copy,slice等
- 设置字节顺序
- 构造实例
- 操作位置指针
读写功能
ByteBuf通过readIndex和writeIndex协助缓冲区读写操作。0 <= readIndex <= writeIndex <= capacity 。
ByteBuf读写方法分为:
- getXXX(int index):返回指定索引位置的指定类型的值。不改变readIndex和writeIndex。
- readXXX():读取指定类型的值,会修改readIndex的值,根据指定类型增加readIndex。
- setXXX(int index,XXX value):设置指定索引位置的值,不改变readIndex和writeIndex。
- writeXXX(XXX value):写入指定类型的值。会修改writeIndex的值,根据指定类型增加writeIndex。
在每次put操作时,都需要检查剩余空间,如果空间不足,则会创建一个新的ByteBuf
扩容与收缩
- discardReadBytes():收回丢弃空间,内部copy,移动readIdnex,writeIndex。
- clear():清空缓冲区,不填充任何信息,仅修改readIndex,writeIndex为0
- markReaderIndex()和markWriterIndex():
- resetReaderIndex()和resetWriterIndex():
查找
- indexOf(...)
- bytesBefore(...)
- forEachByte(...)
Derived buffers
- duplicate():与源Buffer共享缓冲区。
- copy(...):不与源Buffer共享缓冲区。
- slice(...):与源Buffer共享缓冲区。
ByteBuffer互转换
- nioBuffer(...)
- nioBuffers(...)
ByteBuf源码
ByteBuf结构
继承关系
分类
内存分配角度:
- 堆内存(HeapByteBuf)
内存分配和回收速度快,可以被JVM回收。由于需要做一次内核Copy,性能低。
- 直接内存(DirectByteBuf)
堆外内存,内存分配和回收速度快。不需要做一次内核Copy,性能高。
最佳实践:I/O通信读写缓冲区用DirectByteBuf;业务消息编解码使用HeapByteBuf。
内存回收角度
- 基于池ByteBuf:可以重用ByteBuf。
- 普通ByteBuf
AbstractByteBuf
ResourceLeakDetector leakDetector;
用于检测对象是否泄漏。
AbstractReferenceCountedByteBuf
ReferenceCountUpdater
UnpooledHeapByteBuf
private final ByteBufAllocator alloc;
byte[] array;
private ByteBuffer tmpNioBuf;
PooledByteBuf<T>
private final Recycler.Handle<PooledByteBuf<T>> recyclerHandle;
protected PoolChunk<T> chunk;
protected long handle;
protected T memory;
protected int offset;
protected int length;
int maxLength;
PoolThreadCache cache;
ByteBuffer tmpNioBuf;
private ByteBufAllocator allocator;
PooledDirectByteBuf
辅助类
ByteBufHolder
ByteBufHolder是ByteBuf的容器。
ByteBufAllocator
字节缓冲区分配器。
PooledByteBufAllocator
UnpooledByteBufAllocator
CompositeByteBuf
多个ByteBuf实例组装视图。
ByteBufUtil
工具类