Netty 4字节缓冲区可写字节澄清

  • 本文关键字:字节 缓冲区 Netty netty
  • 更新时间 :
  • 英文 :


我正在努力理解ByteBuffer。下面是程序。

ByteBuf heapBuff = Unpooled.buffer(18);
System.out.println("writableBytes " + heapBuff.writableBytes());
heapBuff.writeCharSequence("RAJKUMAR NATARAJAN TESTE", Charset.defaultCharset());
System.out.println("readableBytes " + heapBuff.readableBytes());
System.out.println("writableBytes " + heapBuff.writableBytes());

上述程序的输出是

writableBytes 18
readableBytes 24
writableBytes 104

writableBytes的计算逻辑是什么。

缓冲区写入将检查它们是否有足够的可写字节来容纳数据,如果没有,则会增加后台缓冲区的大小。这就是在检查是否有足够的可写字节时所称的,也是容量增加的原因。如果你把24加到104=128,这是2的幂。

AbstractByteBuf.class

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);
}

资源:

字节跳动JavaDoc

AbstractByteBuf.class(github(