实际上,7种基本类型(boolean除外)都有自己的缓冲区实现,不过因为功能、方法、原理基本一致,所以仅讨论ByteBuffer。
Netty Api地址:http://netty.io/5.0/api/
一 内容概述
NIO ByteBuffer的概述。
Netty ByteBuf的详细讲述,包括读、写、扩容、mark、reset、duplicate等操作。
核心类的源码分析。
堆内存缓冲区、直接内存缓冲区。
二 NIO ByteBuffer的局限性
1. 长度固定
ByteBuffer一旦分配完成,他的容量不能动态扩展和收缩,当需要编码的POJO对象大于ByteBuffer容量是,会发生索引越界异常。
2. 使用复杂
ByteBuffer只有一个标识位置的指针position,读写的时候需要手工调用flip()和rewind()等方法,使用时需要非常谨慎的使用这些api,否则很容出现错误
3. API功能有限
一些高级、实用的特性,ByteBuffer不支持,需要开发者自己编程实现。
为了弥补这些不足,Netty提供了自己的ByteBuf实现。
三 ByteBuf原理
1. 基本功能
java 7种基本类型、byte数组、ByteBuffer等的读写
java 7种基本类型、byte数组、ByteBuffer等的读写
缓冲区资深的copy和slice等
设置网络字节序
构造缓冲区实例
操作位置指针等方法
2. NIO的flip
1) 示例代码
ByteBuffer buffer = ByteBuffer.allocate(1024) ;
String content = "伍正飞";
buffer.put(content.getBytes()) ;
buffer.flip() ;
byte[] newArray = new byte[buffer.remaining()] ;
buffer.get(newArray) ;
String value = new String(newArray);
System.err.println(value);
2) flip操作
a) Flip之前

b) Flip之后

读取的内容是从position到limit之间的内容,所以每次写完缓冲区以后,都需要调用flip才能正确的读取数据
3. Netty的ByteBuf
1) 简介
ByteBuf通过两个指针协助读写操作,读操作使用readerIndex,写操作使用writerIndex。
readerIndex、writerIndex初始值是0,写入数据时writerIndex增加,读取数据时readerIndex增加,但是readerIndex不会超过writerIndex。
读取之后,0-readerIndex之间的空间视为discard的,调用discardReadByte方法可以释放这一部分空间,作用类似于ByteBuffer的compact方法。
readerIndex-writerIndex之间的数据是可读的,等价于ByteBuffer中position-limit之间的数据。
writerIndex-capacity之间的空间是可写的,等价于ByteBuffer中limit-capacity之间的空间。
读只影响readerIndex、写只影响writerIndex,读写之间不需要调整指针位置,所以相较于NIO的ByteBuffer,可以极大的简化读写操作。
2) 读写操作
a) 初始化

b) 写入N个字节以后

c) 写入N个字节,读取M个字节以后

d) 写入N个字节,读取M个字节,调用discardReadBytes以后

调用discardReadBytes会发生字节数组的内存复制,所以频繁调用会导致性能下降。
e) clear以后

3) 动态扩容
a) NIO的ByteBuffer
写数据时,如果buffer的空间不足,会抛出BufferOverflowException,以下为ByteBuffer中的put源码:
public ByteBuffer put(byte[] src, int offset, int length) {
checkBounds(offset, length, src.length);
if (length > remaining())
throw new BufferOverflowException();
int end = offset + length;
for (int i = offset; i < end; i++)
this.put(src[i]);
return this;
}
为了避免抛出BufferOverflowException异常,通常在put前都需要对剩余空间进行校验,并将之前ByteBuffer中的数据复制到新的缓冲区中,然后释放之前ByteBuffer的空间,示例代码如下:
int needSize = 1024 ;
if( buffer.remaining() < needSize ){
int extraSize = needSize > 128 ? needSize : 128 ;
ByteBuffer newByteBuffer = ByteBuffer.allocate(buffer.capacity() + extraSize ) ;
buffer.flip() ;
newByteBuffer.put(buffer) ;
buffer = newByteBuffer ;
}
b) Netty的ByteBuf
ByteBuf对write操作进行了封装,有ByteBuf的write操作负责进行剩余咳哟好难过空间的校验,如果可用缓冲区不足,ByteBuf会自动进行动态扩展。对于使用者而言不需要关心底层的校验和扩展细节,只需要不超过capacity即可。
ByteBuf中writeBytes示例代码如下(以下代码摘抄自AbstractByteBuf,为ByteBuf的子类)。
public ByteBuf writeBytes(byte[] src) {
writeBytes(src, 0, src.length);
return this;
}
public ByteBuf writeBytes(byte[] src, int srcIndex, int length) {
ensureWritable(length);
setBytes(writerIndex, src, srcIndex, length);
writerIndex += length;
return this;
}
public ByteBuf ensureWritable(int minWritableBytes) {
if (minWritableBytes < 0) {
throw new IllegalArgumentException(
String.format("minWritableBytes: %d (expected: >= 0)", minWritableBytes));
}
ensureWritable0(minWritableBytes);
return this;
}
final void ensureWritable0(int minWritableBytes) {
ensureAccessible();
if (minWritableBytes <= writableBytes()) {
return;
}
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);
}
4) Mark和Reset
对缓冲区进行读操作时,有的时候我们需要对之前的操作进行回滚,读操作并不会改变缓冲区的内容,回滚主要是重新设置索引信息。
a) NIO的Mark和Reset
Mark:将当前的位置指针被分到mark变量中。
Reset:恢复位置指针为mark中的变量值。
源码如下:
public final Buffer mark() {
mark = position;
return this;
}
public final Buffer reset() {
int m = mark;
if (m < 0)
throw new InvalidMarkException();
position = m;
return this;
}
b) Netty的mark和reset
ByteBuf有readerIndex、writerIndex,所以有四个相应的方法
markReaderIndex: 将当前readerIndex备份到markedReaderIndex中
resetReaderIndex: 将当前readerIndex设置为markedReaderIndex
markWriterIndex: 将当前readerIndex备份到markedWriterIndex中
resetWriterIndex: 将当前readerIndex设置为markedWriterIndex
示例代码
public ByteBuf markReaderIndex() {
markedReaderIndex = readerIndex;
return this;
}
@Override
public ByteBuf resetReaderIndex() {
readerIndex(markedReaderIndex);
return this;
}
@Override
public ByteBuf markWriterIndex() {
markedWriterIndex = writerIndex;
return this;
}
@Override
public ByteBuf resetWriterIndex() {
writerIndex = markedWriterIndex;
return this;
}
5) duplicate、copy、slice、nioBuffer
a) duplicate
返回当前ByteBuf的复制对象,复制后返回的ByteBuf和当前操作的ByteBuf共享缓冲区,但维护自己独立的读写索引。当修改其中一个ByteBuf的内容时,另一个也会改变,即双方持有的是同一个对象的引用。
b) copy
复制一个新的ByteBuf对象,和原有的ByteBuf完全独立,修改以后不会影响两外一个。
c) slice
返回当前ByteBuf的可读子缓冲区,即从readerIndex到writerIndex的ByteBuf,返回的ByteBuf和原有缓冲区共享内容,但是维护独立的索引。当修改其中一个ByteBuf的内容时,另一个也会改变,即双方持有的是同一个对象的引用。
d) nioBuffer
将当前ByteBuf可读的缓冲区转换成NIO的ByteBuffer,两者持有相同同内容的引用,对ByteBuffer的读写操作不会修改原ByteBuf的读写索引
四 源码分析
1. ByteBuf的类结构

a) AbstractByteBuf
ByteBuf的公共属性和功能都会在AbstractByteBuf中实现。
b) AbstractReferenceCountedByteBuf
主要是对引用进行计数,类似于JVM内存回收的对象引用计数器,用于跟踪对象的分配和销毁,作自动内存回收。
c) UnpooledHeapByteBuf
UnpooledHeapByteBuf是基于堆内存进行内存分配的字节缓冲区,没有使用基于对象池计数实现,所以每次I/O的读写都会创建一个新的UnpooledHeapByteBuf。注意,频繁的进行大块内存的分配和回收对性能会造成一定影响。
相比于PooledHeapByteBuf,UnpooledHeapByteBuf的实现更加简单,也不容易出现内存管理的问题,所以才性能满足的情况下,推荐使用UnpooledHeapByteBuf
2. 堆内存和直接内存
1) 堆内存字节缓冲区(HeapByteBuf)
内存的分配和回收速度快,可以被JVM自动回收,缺点是如果进行socket的I/O读写,需要额外做一次内存复制,将堆内存对应的字节缓冲区复制到内核Channel中,性能会有一定的下降
2) 直接内存字节缓冲区(DirectByteBuf)
非堆内存,它在堆外进行内存分配,相比于堆内存,它的分配和回收速度会慢一些,但是将他写入或者从SocketChannel中读取出是,由于少了一次内存复制,速度比堆内存快。
3) ByteBuf的最佳实践
在I/O通信线程的读写缓冲区中使用DirectByteBuf,后端业务消息的编码使用HeapByteBuf,这样的组合性能最优
3. 基于对象池的ByteBuf
基于对象池的ByteBuf可以重用ByteBuf对象,他自己维护了一个内存池,可以循环利用创建的ByteBuf,提升内处的使用效率,降低由于高负载导致的频繁GC。测试表明使用内存池的Netty在高负载、大并发的冲击下内存和GC更加平稳。
使用基于对象池的ByteBuf,内存池的管理和维护变得更加复杂,使用时需要谨慎。