Java原生NIO库中的ByteBuffer存在的一些缺点,导致在使用时不是很方面,例如:
- ByteBuffer中只有一个指针,用户在读取时需要调用flip()等操作移动指针的位置,否则很容易导致读取出的数据不正确
- ByteBuffer在put操作时不能自动扩充容量,即只能在创建时就确定,在后续的使用过程中不太灵活
Netty实现了自己的缓冲区类——ByteBuf
其中,使用了两个指针,一个是读指针——readerIndex,一个是写指针——writerIndex。两个指针之间互不干扰。通过这两个指针,可以将整个缓冲区划分成三个区域,0-readerIndex指的是已经读取完数据的区域,这部分区域可以复用;readerIndex-writerIndex指的是可读区域;writerIndex-capacity指的是可写区域。因为对缓冲区的创建和释放是个耗时的操作,所以为了能尽可能地复用缓存区域,ByteBuf提供了一个discardReadBytes操作,这个操作会重新整理这片缓冲区的内存,将可读区域的内存复制到缓冲区开始的位置,整理完成后readerIndex变为0,可写区域变大,如下是在AbstractByteBuf中关于discardReadBytes的实现代码,不同ByteBuf的实现类中处理机制可能不一样:
public ByteBuf discardReadBytes() {
this.ensureAccessible();
if (this.readerIndex == 0) {
return this;
} else {
if (this.readerIndex != this.writerIndex) {
//内存复制操作
this.setBytes(0, this, this.readerIndex, this.writerIndex - this.readerIndex);
this.writerIndex -= this.readerIndex;
this.adjustMarkers(this.readerIndex);
this.readerIndex = 0;
} else {
this.adjustMarkers(this.readerIndex);
this.writerIndex = this.readerIndex = 0;
}
return this;
}
}
当进行读操作的时候,可能需要对之前的操作进行回滚时。回滚操作实际上就是重新设