[Netty源码] ByteBuf相关问题 (十)

2023-10-20 06:40

本文主要是介绍[Netty源码] ByteBuf相关问题 (十),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

      • 1.ByteBuf介绍
      • 2.ByteBuf分类
        • 2.1 AbstractByteBuf
        • 2.2 AbstractReferenceCountedByteBuf
        • 2.3 UnpooledHeapByteBuf
        • 2.4 UnpooledDirectByteBuf
        • 2.5 PooledDirectByteBuf

1.ByteBuf介绍

字节缓冲区, jdk NIO的ByteBuffer比较复杂, netty重新设计了ByteBuf用以代替ByteBuffer

ByteBuf主要是通过readerIndex 和 writerIndex两个指针进行数据的读和写, 整个ByteBuf被这两个指针最多分成三个部分, 分别是可丢弃部分, 可读部分和可写部分

在这里插入图片描述

  • readerIndex和writerIndex初始值都是0, 随着写入writerIndex的增加, readerIndex的增加。

  • 0 ~ readerIndex之间就被视为discard的, 调用discardReadByte 方法, 可以释放这个空间, readerIndex = 0, writerIndex = writerIndex - readerIndex

  • 扩容设计: Nio 的 ByteBuffer没有扩容设计, 底层是数组, 会报BufferOverflowExeption错误, ByteBuf会自动进行动态扩展

2.ByteBuf分类

  • 从内存回收的角度来看: Pooled和Unpooled: 基于对象池的ByteBuf和普通ByteBuf
  • 从内存分配角度来看: heap和direct: 堆内存和直接内存
  • 从如何读取数据角度来看: unsafe和非unsafe: unsafe可以直接拿到byteBuf的内存地址, 不会依赖jdk底层的unsafe, unsafe通过内存地址+偏移量, 非unsafe通过数组+下标或者说jdk底层ButBufferApi获取对应的数据

在这里插入图片描述

2.1 AbstractByteBuf

AbstractByteBuf 是ByteBuf骨架的一个实现

在这里插入图片描述

成员变量

    // 用于检测对象是否泄漏static final ResourceLeakDetector<ByteBuf> leakDetector = new ResourceLeakDetector<ByteBuf>(ByteBuf.class);// 读操做 和 写操作 的位置指针int readerIndex;private int writerIndex;// 读操作 和 写操作 的标记,可以通过reset()回到标记的地方private int markedReaderIndex;private int markedWriterIndex;// 最大容量private int maxCapacity;

一些简单的方法

    @Overridepublic ByteBuf readerIndex(int readerIndex) {if (checkBounds) {checkIndexBounds(readerIndex, writerIndex, capacity());}this.readerIndex = readerIndex;return this;}@Overridepublic ByteBuf writerIndex(int writerIndex) {if (checkBounds) {checkIndexBounds(readerIndex, writerIndex, capacity());}this.writerIndex = writerIndex;return this;}@Overridepublic ByteBuf clear() {readerIndex = writerIndex = 0;return this;}

在这里插入图片描述

通过一个_getByte()抽象类让实现类实现这个方法, 做不同的功能

2.2 AbstractReferenceCountedByteBuf

作用主要是对ButeBuf引用进行计数,用于跟踪对象的分配及销毁。

在这里插入图片描述

  • 每调用一次 retain() 方法,引用计数器就加1
  • 由于 refCnt 初始值为1,每次申请加1,释放减1,当申请数等于释放数时,对象被回收,故 refCnt 不可能为0。如果为0,说明对象被错误、意外的引用了,抛出异常*
    public ByteBuf retain() {for (;;) {int refCnt = this.refCnt;if (refCnt == 0) {throw new IllegalReferenceCountException(0, 1);}if (refCnt == Integer.MAX_VALUE) {throw new IllegalReferenceCountException(Integer.MAX_VALUE, 1);}if (refCntUpdater.compareAndSet(this, refCnt, refCnt + 1)) {break;}}return this;}public final boolean release() {for (;;) {int refCnt = this.refCnt;if (refCnt == 0) {throw new IllegalReferenceCountException(0, -1);}if (refCntUpdater.compareAndSet(this, refCnt, refCnt - 1)) {if (refCnt == 1) {// 垃圾回收deallocate();return true;}return false;}}}
2.3 UnpooledHeapByteBuf

UnpooledHeapByteBuf 就是普通的堆内存ByteBuf, 没有内存池, 没有堆外内存。

成员变量

    // 用于UnpooledHeapByteBuf内存分配private final ByteBufAllocator alloc;// 缓冲区private byte[] array;// Java NIO的ByteBuffer,用于Netty的ByteBuf到NIO的ByteBuffer转换private ByteBuffer tmpNioBuf;

动态扩展缓冲区

  1. newCapacity > oldCapacity,直接创建一个新数组,拷贝过去就行了
  2. newCapacity == oldCapacity,不做处理
  3. newCapacity < oldCapacity,先判断readerIndex,如果readerIndex大于等于newCapacity,说明没有数据需要复制到缓冲区,直接设置readerIndex和writerIndex的值为newCapacity即可;当readerIndex小于newCapacity时,readerIndex到writerIndex之间的数据需要复制到新的byte数组,这个时候,如果writerIndex - readerIndex > newCapacity,就会发生数组下标越界,为了防止越界,当writerIndex > newCapacity时,令writerIndex = newCapacity,然后做 byte 数组赋值操作。最后,替换掉ByteBuf中持有的 byte数组引用,并令NIO 的 ByteBuffer为 null。
    public ByteBuf capacity(int newCapacity) {ensureAccessible();// 1. 对入参做合法性校验if (newCapacity < 0 || newCapacity > maxCapacity()) {throw new IllegalArgumentException("newCapacity: " + newCapacity);}int oldCapacity = array.length;if (newCapacity > oldCapacity) {// 2. byte数组copy,然后替换掉原来的byte数组byte[] newArray = new byte[newCapacity];System.arraycopy(array, 0, newArray, 0, array.length);setArray(newArray);} else if (newCapacity < oldCapacity) {// 如果新容量小于老容量,则不需要动态扩展,但是需要截取当前缓冲区创建一个新的子缓冲区byte[] newArray = new byte[newCapacity];int readerIndex = readerIndex();if (readerIndex < newCapacity) {int writerIndex = writerIndex();if (writerIndex > newCapacity) {// 如果writerIndex大于newCapacity,则有可能发生越界,这里直接截断writerIndex(writerIndex = newCapacity);}System.arraycopy(array, readerIndex, newArray, readerIndex, writerIndex - readerIndex);} else {// 如果readerIndex大于等于新的capacity,说明没有数据需要复制到新缓冲区,直接将readerIndex和writerIndex设置为newCapacity即可setIndex(newCapacity, newCapacity);}setArray(newArray);}return this;}private void setArray(byte[] initialArray) {array = initialArray;tmpNioBuf = null;}

字节数组复制

  • 在AbstractByteBuf中的读写操作中, 具体的读写操作为子类实现的。

  • UnpooledHeapByteBuf 写操作中, 首先检查入参, 然后将数据copy到ByteBuf的byte数组中。

  • UnpooledHeapByteBuf 读操作中, 首先检查入参, 然后将ByteBuf的byte数组copy到指定的byte数组中。

   public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) {// 根据AbstractByteBuf的写操作可知,index为writerIndexcheckSrcIndex(index, length, srcIndex, src.length);System.arraycopy(src, srcIndex, array, index, length);return this;}protected final void checkSrcIndex(int index, int length, int srcIndex, int srcCapacity) {checkIndex(index, length);if (srcIndex < 0 || srcIndex > srcCapacity - length) {throw new IndexOutOfBoundsException(String.format("srcIndex: %d, length: %d (expected: range(0, %d))", srcIndex, length, srcCapacity));}}protected final void checkIndex(int index, int fieldLength) {ensureAccessible();if (fieldLength < 0) {throw new IllegalArgumentException("length: " + fieldLength + " (expected: >= 0)");}// writerIndex + length > capacity,数组下表越界if (index < 0 || index > capacity() - fieldLength) {throw new IndexOutOfBoundsException(String.format("index: %d, length: %d (expected: range(0, %d))", index, fieldLength, capacity()));}}// 读操作时,将字节数组copy出去public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) {checkDstIndex(index, length, dstIndex, dst.length);System.arraycopy(array, index, dst, dstIndex, length);return this;}

Netty 的 ByteBuf 转换为 NIO 的 ByteNuffer

利用byte数组创建一个新的ByteBuffer, 并调用slice方法, 清除 discard 区域。

    public ByteBuffer nioBuffer(int index, int length) {ensureAccessible();// slice():copy一个原来的position到limit之间的有效数据,创建一个新的ByteBufferreturn ByteBuffer.wrap(array, index, length).slice();}public static ByteBuffer wrap(byte[] array, int offset, int length) {try {return new HeapByteBuffer(array, offset, length);} catch (IllegalArgumentException x) {throw new IndexOutOfBoundsException();}}
2.4 UnpooledDirectByteBuf

UnpooledDIrectByteBuf是基于堆外内存创建的。

这里使用 ByteBuffer 存储数据, 而UnpooledHeapByteBuf 使用字节数组, 这里的ByteBuffer使用的是NIO的DirectByteBuffer, 需要手动释放内存。

成员变量

    // ByteBuf内存分配private final ByteBufAllocator alloc;// 这里跟UnpooledHeapByteBuf不同,这里使用的是NIO的ByteBuffer存储字节数组private ByteBuffer buffer;private ByteBuffer tmpNioBuf;private int capacity;//用于标记ByteBuffer是否释放了(这里使用堆外内存创建ByteBuffer,需要自己做垃圾回收)private boolean doNotFree;

动态扩展缓冲区

不同的是这里使用的是ByteBuffer而不是byte数组。

    public ByteBuf capacity(int newCapacity) {ensureAccessible();// 1. 校验粗人惨if (newCapacity < 0 || newCapacity > maxCapacity()) {throw new IllegalArgumentException("newCapacity: " + newCapacity);}int readerIndex = readerIndex();int writerIndex = writerIndex();int oldCapacity = capacity;if (newCapacity > oldCapacity) {// 这里直接创建一个新的ByteBuffer,将老的ByteBuffer数据copy过去ByteBuffer oldBuffer = buffer;// 创建一个DirectByteBufferByteBuffer newBuffer = allocateDirect(newCapacity);// 设置position和limit的值oldBuffer.position(0).limit(oldBuffer.capacity());newBuffer.position(0).limit(oldBuffer.capacity());newBuffer.put(oldBuffer);newBuffer.clear();// 替换老的ByteBuffer并释放掉老的ByteBuffersetByteBuffer(newBuffer);} else if (newCapacity < oldCapacity) {// 这里跟UnpooledHeapByteBuf处理是一样的,详细看UnpooledHeapByteBufByteBuffer oldBuffer = buffer;ByteBuffer newBuffer = allocateDirect(newCapacity);if (readerIndex < newCapacity) {if (writerIndex > newCapacity) {writerIndex(writerIndex = newCapacity);}oldBuffer.position(readerIndex).limit(writerIndex);newBuffer.position(readerIndex).limit(writerIndex);newBuffer.put(oldBuffer);newBuffer.clear();} else {setIndex(newCapacity, newCapacity);}setByteBuffer(newBuffer);}return this;}// 创建DirectByteBufferprotected ByteBuffer allocateDirect(int initialCapacity) {return ByteBuffer.allocateDirect(initialCapacity);}private void setByteBuffer(ByteBuffer buffer) {ByteBuffer oldBuffer = this.buffer;if (oldBuffer != null) {if (doNotFree) {doNotFree = false;} else {// 释放oldByteBufferfreeDirect(oldBuffer);}}this.buffer = buffer;tmpNioBuf = null;capacity = buffer.remaining();}

字节数组复制

  • 在AbstractByteBuf中的读写操作中, 具体的读写操作为子类实现的。
  • UnpooledDirectByteBuf 写操作, 先验证入参, 再创建一个临时的ByteBuffer, 这个ByteBuffer与buffer的content共用, 向tmpBuf中写数据相当于向buffer写数据。
  • UnpooledDirectByteBuf 读操作, 先验证入参, 然后创建出一个临时的 ByteBuffer, 这个临时的 ByteBuffer 做读操作。
    public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) {// 参数校验checkSrcIndex(index, length, srcIndex, src.length);// 创建一个临时的tmpBufByteBuffer tmpBuf = internalNioBuffer();tmpBuf.clear().position(index).limit(index + length);tmpBuf.put(src, srcIndex, length);return this;}private ByteBuffer internalNioBuffer() {ByteBuffer tmpNioBuf = this.tmpNioBuf;if (tmpNioBuf == null) {// 令tempNioBuf和buffer共用同一个ByteBuffer内容,修改了tmpNioByteBuf,也等同于修改了buffer// 但是它们的position、limit都是独立的this.tmpNioBuf = tmpNioBuf = buffer.duplicate();}return tmpNioBuf;}public ByteBuf readBytes(byte[] dst, int dstIndex, int length) {checkReadableBytes(length);getBytes(readerIndex, dst, dstIndex, length, true);readerIndex += length;return this;}private void getBytes(int index, byte[] dst, int dstIndex, int length, boolean internal) {checkDstIndex(index, length, dstIndex, dst.length);if (dstIndex < 0 || dstIndex > dst.length - length) {throw new IndexOutOfBoundsException(String.format("dstIndex: %d, length: %d (expected: range(0, %d))", dstIndex, length, dst.length));}ByteBuffer tmpBuf;if (internal) {tmpBuf = internalNioBuffer();} else {tmpBuf = buffer.duplicate();}tmpBuf.clear().position(index).limit(index + length);tmpBuf.get(dst, dstIndex, length);}

Netty 的 ByteBuf 转换为 NIO 的 ByteNuffer

这里直接拿buufer的content创建一个新的ByteBuffer。

    public ByteBuffer nioBuffer(int index, int length) {return ((ByteBuffer) buffer.duplicate().position(index).limit(index + length)).slice();}public ByteBuffer duplicate() {return new DirectByteBuffer(this, this.markValue(), this.position(), this.limit(), this.capacity(), 0);}
2.5 PooledDirectByteBuf

PooledDirectByteBuf基于内存池实现, 与UnpooledDirectByteBuf唯一的不同就是缓冲区的分配和销毁策略

创建字节缓冲区

由于采用内存池实现, 不可new创建实例, 而是从内存池中获取, 然后设置引用计数器的值。

    static PooledDirectByteBuf newInstance(int maxCapacity) {PooledDirectByteBuf buf = RECYCLER.get();buf.setRefCnt(1);buf.maxCapacity(maxCapacity);return buf;}

复制新的字节缓冲区

复制新的字节缓冲区时候, 也需要通过内存池创建一个字节缓冲区, 然后复制。

    public ByteBuf copy(int index, int length) {// 参数校验checkIndex(index, length);// 从内存池中创建一个ByteBufByteBuf copy = alloc().directBuffer(length, maxCapacity());// 复制操作copy.writeBytes(this, index, length);return copy;}

这篇关于[Netty源码] ByteBuf相关问题 (十)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/245367

相关文章

Spring 中 BeanFactoryPostProcessor 的作用和示例源码分析

《Spring中BeanFactoryPostProcessor的作用和示例源码分析》Spring的BeanFactoryPostProcessor是容器初始化的扩展接口,允许在Bean实例化前... 目录一、概览1. 核心定位2. 核心功能详解3. 关键特性二、Spring 内置的 BeanFactory

SpringBoot利用dynamic-datasource-spring-boot-starter解决多数据源问题

《SpringBoot利用dynamic-datasource-spring-boot-starter解决多数据源问题》dynamic-datasource-spring-boot-starter是一... 目录概要整体架构构想操作步骤创建数据源切换数据源后续问题小结概要自己闲暇时间想实现一个多租户平台,

VSCode中C/C++编码乱码问题的两种解决方法

《VSCode中C/C++编码乱码问题的两种解决方法》在中国地区,Windows系统中的cmd和PowerShell默认编码是GBK,但VSCode默认使用UTF-8编码,这种编码不一致会导致在VSC... 目录问题方法一:通过 Code Runner 插件调整编码配置步骤方法二:在 PowerShell

mybatis-plus分页无效问题解决

《mybatis-plus分页无效问题解决》本文主要介绍了mybatis-plus分页无效问题解决,原因是配置分页插件的版本问题,旧版本和新版本的MyBatis-Plus需要不同的分页配置,感兴趣的可... 昨天在做一www.chinasem.cn个新项目使用myBATis-plus分页一直失败,后来经过多方

Flask解决指定端口无法生效问题

《Flask解决指定端口无法生效问题》文章讲述了在使用PyCharm开发Flask应用时,启动地址与手动指定的IP端口不一致的问题,通过修改PyCharm的运行配置,将Flask项目的运行模式从Fla... 目录android问题重现解决方案问题重现手动指定的IP端口是app.run(host='0.0.

Seata之分布式事务问题及解决方案

《Seata之分布式事务问题及解决方案》:本文主要介绍Seata之分布式事务问题及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Seata–分布式事务解决方案简介同类产品对比环境搭建1.微服务2.SQL3.seata-server4.微服务配置事务模式1

mysql关联查询速度慢的问题及解决

《mysql关联查询速度慢的问题及解决》:本文主要介绍mysql关联查询速度慢的问题及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录mysql关联查询速度慢1. 记录原因1.1 在一次线上的服务中1.2 最终发现2. 解决方案3. 具体操作总结mysql

一文教你解决Python不支持中文路径的问题

《一文教你解决Python不支持中文路径的问题》Python是一种广泛使用的高级编程语言,然而在处理包含中文字符的文件路径时,Python有时会表现出一些不友好的行为,下面小编就来为大家介绍一下具体的... 目录问题背景解决方案1. 设置正确的文件编码2. 使用pathlib模块3. 转换路径为Unicod

Spring MVC跨域问题及解决

《SpringMVC跨域问题及解决》:本文主要介绍SpringMVC跨域问题及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录跨域问题不同的域同源策略解决方法1.CORS2.jsONP3.局部解决方案4.全局解决方法总结跨域问题不同的域协议、域名、端口

SpringBoot自定义注解如何解决公共字段填充问题

《SpringBoot自定义注解如何解决公共字段填充问题》本文介绍了在系统开发中,如何使用AOP切面编程实现公共字段自动填充的功能,从而简化代码,通过自定义注解和切面类,可以统一处理创建时间和修改时间... 目录1.1 问题分析1.2 实现思路1.3 代码开发1.3.1 步骤一1.3.2 步骤二1.3.3