在DefaultChannelConfig中,

netty源码:(48) ChannelHandlerContext的alloc方法得到的ByteBufAllocator类型是如何确定的?_.net


而ByteBuffAllocator中定义的DEFAULT如下:

netty源码:(48) ChannelHandlerContext的alloc方法得到的ByteBufAllocator类型是如何确定的?_java_02

ByteBufUtil类中

netty源码:(48) ChannelHandlerContext的alloc方法得到的ByteBufAllocator类型是如何确定的?_.net_03


首先获取io.netty.allocator.type(可按下图配置)

netty源码:(48) ChannelHandlerContext的alloc方法得到的ByteBufAllocator类型是如何确定的?_java_04

看是pooled还是unpooled,如果没有,则判断是否是安卓平台,是的话取unpooled,否则取pooled.

最终会返回UnpooledByteBufAllocator.DEFAULT或者PooledByteBufAllocator.DEFAULT.

然后它们再根据相关配置决定返回DirectByteBuf还是HeapByteBuf

netty源码:(48) ChannelHandlerContext的alloc方法得到的ByteBufAllocator类型是如何确定的?_.net_05


而使用DirectByteBuf还是HeapByteBuf由如下逻辑确定:

netty源码:(48) ChannelHandlerContext的alloc方法得到的ByteBufAllocator类型是如何确定的?_.net_06


也就是默认使用DirectByteBuf,如果设置了io.netty.noPreferDirect参数,则以这个参数为准,如果设置为true,则会使用HeapByteBuf