Netty的Buffer为什么好用
典型回答 在网络编程中,基本都是基于TCP报文的字节流的操作,所以Java的NIO又新增了ByteBuffer,只不过Java原生的ByteBuffer,非常难操作,也不能扩缩容,所以Netty又重新封装了自己的Bytebuf,除了性能上的优势之外,Netty的Buffer在使用上相对于NIO也非常简洁,有如下特点: 动态扩缩容 顾名思义,Netty中的ByteBuffer可以像Java中的ArrayList一样,根据写入数据的字节数量,自动扩容。代码如下所示: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 final void ensureWritable0(int minWritableBytes) { final int writerIndex = writerIndex(); final int targetCapacity = writerIndex + minWritableBytes; // using non-short-circuit & to reduce branching - this is a hot path and targetCapacity should rarely overflow if (targetCapacity >= 0 & targetCapacity <= capacity()) { ensureAccessible(); return; } if (checkBounds && (targetCapacity < 0 || targetCapacity > maxCapacity)) { ensureAccessible(); throw new IndexOutOfBoundsException(String.format( "writerIndex(%d) + minWritableBytes(%d) exceeds maxCapacity(%d): %s", writerIndex, minWritableBytes, maxCapacity, this)); } // Normalize the target capacity to the power of 2. final int fastWritable = maxFastWritableBytes(); int newCapacity = fastWritable >= minWritableBytes ? writerIndex + fastWritable : alloc().calculateNewCapacity(targetCapacity, maxCapacity); // Adjust to the new capacity. 【此处进行扩容】 capacity(newCapacity); } 这个在编写代码的时候,满足ByteBuf最大缓冲区的情况下,我们可以毫无顾忌地调用#write方法增加字节,而不用手动去check容量满足,然后去重新申请 ...