netty学习笔记二——ByteBuf类原理

ByteBuf提供对于原始数组(byte[])的抽象封装,它是一个byte数组的缓冲区。

ByteBuf通过两个位置指针完成缓冲区的读写操作,readerIndex用于读操作,writerIndex用以写操作。下面展示了如何通过两个指针将缓冲区分为三个区域。

       +-------------------+------------------+------------------+
       | discardable bytes |  readable bytes  |  writable bytes  |
       |                   |     (CONTENT)    |                  |
       +-------------------+------------------+------------------+
       |                   |                  |                  |
       0      <=      readerIndex   <=   writerIndex    <=    capacity    

Readable bytes:真正意义上存储数据的地方,任何读(read)操作或者跳过(skip)操作都会根据读取内容增大readerIndex的值,当传入参数也是ByteBuf并且没有设置index时,writerIndex也会同步增加。当读取内容为空时,会抛出IndexOutOfBoundsException。

Writable bytes:用以写数据的区域,任何写操作都会都会根据写入内容增大writerIndex的值。当传入参数也是ByteBuf并且没有设置index时,readerIndex也会同步增加。当可写入内容不够时,会抛出IndexOutOfBoundsException。

Discardable bytes:已经被read操作读取过的数据,该区域初始值为0。当读操作结束的时候,该区域的大小就是当前writerIndex所在的大小。这个区域的数据可以通过discardReadBytes()方法进行回收。如下是清除过程示意。

    BEFORE discardReadBytes()
 
       +-------------------+------------------+------------------+
       | discardable bytes |  readable bytes  |  writable bytes  |
       +-------------------+------------------+------------------+
       |                   |                  |                  |
       0      <=      readerIndex   <=   writerIndex    <=    capacity
 
 
    AFTER discardReadBytes()
 
       +------------------+--------------------------------------+
       |  readable bytes  |    writable bytes (got more space)   |
       +------------------+--------------------------------------+
       |                  |                                      |
  readerIndex (0) <= writerIndex (decreased)        <=        capacity

clear()方法:该方法仅仅将readerIndex和writerIndex简单归零,本身并不清除里面的数据内容。简单示意图如下。

    BEFORE clear()
 
       +-------------------+------------------+------------------+
       | discardable bytes |  readable bytes  |  writable bytes  |
       +-------------------+------------------+------------------+
       |                   |                  |                  |
       0      <=      readerIndex   <=   writerIndex    <=    capacity
 
 
   AFTER clear()
 
       +---------------------------------------------------------+
       |             writable bytes (got more space)             |
       +---------------------------------------------------------+
       |                                                         |
       0 = readerIndex = writerIndex            <=            capacity

猜你喜欢

转载自www.cnblogs.com/magotzis/p/9543612.html