netty学习之二:ByteBuf解读
来源:互联网 发布:淘宝有客服投诉电话 编辑:程序博客网 时间:2024/04/26 23:37
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
,
0 0
- netty学习之二:ByteBuf解读
- netty 学习之bytebuf
- Netty学习之旅----ByteBuf源码解读之初探UnpooledHeapByteBuf、UnpooledDirectByteBuf
- Netty之ByteBuf
- netty(十一)源码分析之ByteBuf 二
- Netty学习之旅----ByteBuf内部结构与API学习
- Netty之ByteBuf综合剖析
- Netty ByteBuf
- Netty ByteBuf
- 共同学习Netty源代码--ByteBuf(一)
- Netty学习12-缓冲区【2】ByteBuf
- netty源码学习第三章:ByteBuf
- netty源码分析 之十一 ByteBuf
- netty(十)源码分析之ByteBuf
- Netty之ByteBuf的创建和释放
- Netty学习之二
- Netty之实现自定义简单的编解码器二(MessageToMessageEncoder<CharSequence>和MessageToMessageDecoder<ByteBuf>)
- Netty 权威指南笔记(五):ByteBuf 源码解读
- Effective STL 学习笔记
- iOS开发网络篇—数据缓存
- dispatch API简单总结
- 8.15作业
- Java Semaphore 信号量
- netty学习之二:ByteBuf解读
- Android事件处理
- iOS开发网络篇—使用ASI框架进行文件下载
- maven repository
- horizontalscrollview
- Android优化笔记
- 通信阶段的总结
- 【转】vc++6.0 字节定义和字节转换。
- ASP.NET合并两个相关联的DataTable