ByteBuf原理跟之前的ByteBuffer原理类似,只是扩展和弥补了ByteBuffer的不足,设计原理:
1、初始化writerIndex,readerIndex为0
2、写入N个字节后:
3、读入M<N字节后:
4、discardReadBytes之后:
5、discardReadBytes前后操作:
源码:
public ByteBuf discardReadBytes() {
ensureAccessible();
if (readerIndex == 0) {
return this;
}
if (readerIndex != writerIndex) {
setBytes(0, this, readerIndex, writerIndex - readerIndex);
writerIndex -= readerIndex;
adjustMarkers(readerIndex);
readerIndex = 0;
} else {
adjustMarkers(readerIndex);
writerIndex = readerIndex = 0;
}
return this;
}
discardReadBytes操作如同compact操作压缩空间,将已经读得数据释放,但是频繁调用discardReadBytes操作会导致性能下降,因为发生了数组字节内存复制
6、clear之后:
7、clear前后:
8、 ByteBuf实现动态空间扩展,看它的实现类AbstractByteBuf代码:
a、写操作之前进行ensureAccessible,ensureWritable校验
@Override
public ByteBuf writeByte(int value) {
ensureAccessible();
ensureWritable(1);
_setByte(writerIndex++, value);
return this;
}
/**
* Should be called by every method that tries to access the buffers content to check
* if the buffer was released before.
*/
protected final void ensureAccessible() {
if (refCnt() == 0) {
throw new IllegalReferenceCountException(0);
}
}
@Override
public ByteBuf ensureWritable(int minWritableBytes) {
if (minWritableBytes < 0) {
throw new IllegalArgumentException(String.format(
"minWritableBytes: %d (expected: >= 0)", minWritableBytes));
}
if (minWritableBytes <= writableBytes()) {
return this;
}
if (minWritableBytes > maxCapacity - writerIndex) {
throw new IndexOutOfBoundsException(String.format(
"writerIndex(%d) + minWritableBytes(%d) exceeds maxCapacity(%d): %s",
writerIndex, minWritableBytes, maxCapacity, this));
}
// Normalize the current capacity to the power of 2.
int newCapacity = alloc().calculateNewCapacity(writerIndex + minWritableBytes, maxCapacity);
// Adjust to the new capacity.
capacity(newCapacity);
return this;
}
重新分配了newCapacity
,