作用
分配一个具有合理初始容量的ByetBuf对象,避免初始容量不合理(过小导致的频繁扩容,过大导致的空间浪费)导致的GC频率加快。
原理
原理:根据之前Channel接收到的数据报文大小进行计算,如果之前ByteBuf被填满,则扩展当前容量;如果连续2次接收到的数据报都小于指定值,则收缩当前的容量,以节约内存。下图为ByteBuf的容量随index的变化曲线,当实际占用的容量超过之前预分配的容量时,index增加,ByteBuf的容量变为index对应的值;缩容同理。
private void record(int actualReadBytes) {
if (actualReadBytes <= SIZE_TABLE[Math.max(0, index - INDEX_DECREMENT - 1)]) {
if (decreaseNow) {
index = Math.max(index - INDEX_DECREMENT, minIndex);
nextReceiveBufferSize = SIZE_TABLE[index];
decreaseNow = false;
} else {
decreaseNow = true;
}
} else if (actualReadBytes >= nextReceiveBufferSize) {
index = Math.min(index + INDEX_INCREMENT, maxIndex);
nextReceiveBufferSize = SIZE_TABLE[index];
decreaseNow = false;
}
}
使用
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
参考: