[Netty源码分析]ByteBuf(一)

  1. java.nio.ByteBuffer缺点
  1. 长度固定,ByteBuffer一旦分配完成,他的容量不能动态扩展和收缩,当需要编码的POJO对象大于ByteBuffer容量是,会发生索引越界异常

  2. 使用复杂,ByteBuffer只有一个标识位置的指针position,读写的时候需要手工调用flip()和rewind()等方法,使用时需要非常谨慎的使用这些api,否则很容出现错误

  3. API功能有限,一些高级、实用的特性,ByteBuffer不支持,需要开发者自己编程实现

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,可以极大的简化读写操作

  1. 读写操作
  1. 初始化
[Netty源码分析]ByteBuf(一)_第1张图片
ByteBuf读写初始化.png
  1. 写入N个字节以后
[Netty源码分析]ByteBuf(一)_第2张图片
ByteBuf写入N个字节.png
  1. 写入N个字节,读取M个字节以后
[Netty源码分析]ByteBuf(一)_第3张图片
ByteBuf写入N个字节,读取M个字节.png
  1. 写入N个字节,读取M个字节,调用discardReadBytes以后
[Netty源码分析]ByteBuf(一)_第4张图片
ByteBuf写入N个字节,读取M个字节,调用discardReadBytes.png

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

  1. clear以后


    [Netty源码分析]ByteBuf(一)_第5张图片
    ByteBuf执行clear.png
  1. 动态扩容
  1. NIO的ByteBuffer
写数据时,如果buffer的空间不足,会抛出BufferOverflowException

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;
}
  1. Netty的ByteBuf

ByteBuf对write操作进行了封装,有ByteBuf的write操作负责进行剩余咳哟好难过空间的校验,如果可用缓冲区不足,ByteBuf会自动进行动态扩展。对于使用者而言不需要关心底层的校验和扩展细节,只需要不超过capacity即可

    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);
    }
  1. Mark和Reset

对缓冲区进行读操作时,有的时候我们需要对之前的操作进行回滚,读操作并不会改变缓冲区的内容,回滚主要是重新设置索引信息

  1. 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;
    }
  1. 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;
  }

  public ByteBuf resetReaderIndex() {
      readerIndex(markedReaderIndex);
      return this;
  }

  public ByteBuf markWriterIndex() {
      markedWriterIndex = writerIndex;
      return this;
  }

  public ByteBuf resetWriterIndex() {
      writerIndex = markedWriterIndex;
      return this;
  }
  1. duplicate、copy、slice、nioBuffer
  1. duplicate:
    返回当前ByteBuf的复制对象,复制后返回的ByteBuf和当前操作的ByteBuf共享缓冲区,但维护自己独立的读写索引.当修改其中一个ByteBuf的内容时,另一个也会改变,即双方持有的是同一个对象的引用

  2. copy:
    复制一个新的ByteBuf对象,和原有的ByteBuf完全独立,修改以后不会影响另外一个

3)slice:
返回当前ByteBuf的可读子缓冲区,即从readerIndex到writerIndex的ByteBuf,返回的ByteBuf和原有缓冲区共享内容,但是维护独立的索引.当修改其中一个ByteBuf的内容时,另一个也会改变,即双方持有的是同一个对象的引用

  1. ByteBuf的类结构
[Netty源码分析]ByteBuf(一)_第6张图片
ByteBuf的类结构.png

常见类:

  1. AbstractByteBuf:ByteBuf的公共属性和功能都会在AbstractByteBuf中实现

  2. AbstractReferenceCountedByteBuf:主要是对引用进行计数,类似于JVM内存回收的对象引用计数器,用于跟踪对象的分配和销毁,作自动内存回收

  3. UnpooledHeapByteBuf:UnpooledHeapByteBuf是基于堆内存进行内存分配的字节缓冲区,没有使用基于对象池计数实现,所以每次I/O的读写都会创建一个新的UnpooledHeapByteBuf.注意,频繁的进行大块内存的分配和回收对性能会造成一定影响

相比于PooledHeapByteBuf,UnpooledHeapByteBuf的实现更加简单,也不容易出现内存管理的问题,所以才性能满足的情况下,推荐使用UnpooledHeapByteBuf

  1. HeapByteBuf(堆内存字节缓冲区):内存的分配和回收速度快,可以被JVM自动回收,缺点是如果进行socket的I/O读写,需要额外做一次内存复制,将堆内存对应的字节缓冲区复制到内核Channel中,性能会有一定的下降

  2. DirectByteBuf(直接内存字节缓冲区):非堆内存,它在堆外进行内存分配,相比于堆内存,它的分配和回收速度会慢一些,但是将他写入或者从SocketChannel中读取出是,由于少了一次内存复制,速度比堆内存快

在I/O通信线程的读写缓冲区中使用DirectByteBuf,后端业务消息的编码使用HeapByteBuf,这样的组合性能最优

你可能感兴趣的:([Netty源码分析]ByteBuf(一))