Netty-源码分析ByteBuf-readSlice和readRetainedSlice使用细节
Posted 征服.刘华强
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Netty-源码分析ByteBuf-readSlice和readRetainedSlice使用细节相关的知识,希望对你有一定的参考价值。
返回从当前readerIndex开始的此缓冲区的子区域的新分片,并将readerIndex增加新分片的大小(=长度)。
另请注意,此方法将不会调用retain(),因此不会增加引用计数。
跟slice极为相似,只是把原始缓冲区的readerIndex进行了增加
@Override
public ByteBuf readSlice(int length)
checkReadableBytes(length);
ByteBuf slice = slice(readerIndex, length);
readerIndex += length;
return slice;
public static void main(String[] args) throws Exception
ByteBufAllocator allocator = PooledByteBufAllocator.DEFAULT;
ByteBuf original = allocator.directBuffer(32);
original.writeByte(1);
original.writeByte(2);
original.writeByte(3);
original.writeByte(4);
//分配子缓冲区
ByteBuf sub = original.readSlice(3);
//原始缓冲区readerIndex=3, readableBytes=1
System.out.println("org.readerIndex = " + original.readerIndex());
System.out.println("org.readableBytes = " + original.readableBytes());
//原始缓冲区引用计数器不变refCnt=1
System.out.println("org.refCnt=" + original.refCnt());
//释放一次
original.release();
public static void main(String[] args) throws Exception
ByteBufAllocator allocator = PooledByteBufAllocator.DEFAULT;
ByteBuf original = allocator.directBuffer(32);
original.writeByte(1);
original.writeByte(2);
original.writeByte(3);
original.writeByte(4);
//分配子缓冲区
ByteBuf sub = original.readRetainedSlice(3);
//原始缓冲区readerIndex=3, readableBytes=1
System.out.println("org.readerIndex = " + original.readerIndex());
System.out.println("org.readableBytes = " + original.readableBytes());
//原始缓冲区引用计数器改变refCnt=2
System.out.println("org.refCnt=" + original.refCnt());
//释放一次
original.release();
//子缓冲区再释放一次
sub.release();
System.out.println("org.refCnt=" + original.refCnt());
QQ群:212320390
以上是关于Netty-源码分析ByteBuf-readSlice和readRetainedSlice使用细节的主要内容,如果未能解决你的问题,请参考以下文章