一、非池化堆内内存分配
下面这小段代码摘自UnpooledByteBufAllocator#newHeapBuffer,通过此方法分析非池化堆内存的分配。
@Override
protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) {
return PlatformDependent.hasUnsafe() ?
new InstrumentedUnpooledUnsafeHeapByteBuf(this, initialCapacity, maxCapacity) :
new InstrumentedUnpooledHeapByteBuf(this, initialCapacity, maxCapacity);
}
解读: 堆内内存分配由newHeapBuffer方法负责,如果平台支持Unsafe则创建InstrumentedUnpooledUnsafeHeapByteBuf,否则创建
InstrumentedUnpooledHeapByteBuf,下图为非池化相关类图,分别从两个类UnpooledDirectByteBuf和UnpooledHeapByteBuf延伸开来。
还是聚集到堆内存的分配上来,主要分析上图中红色部分。InstrumentedUnpooledUnsafeHeapByteBuf和InstrumentedUnpooledHeapByteBuf有啥区别?
InstrumentedUnpooledUnsafeHeapByteBuf
下面看下InstrumentedUnpooledUnsafeHeapByteBuf其内存分配的行为allocateArray().
注解@1 调用了父类UnpooledUnsafeHeapByteBuf的allocateArray()
注解@2 父类UnpooledUnsafeHeapByteBuf调用了PlatformDependent#allocateUninitializedArray
注解@3/@4 Java9以上版本:如果待分配的内存小于1K使用堆内存,待分配的内存大于等于1K使用堆外内存。
Java8以及以下版本全部在堆内存分配
小结: 使用InstrumentedUnpooledUnsafeHeapByteBuf进行内存分配时:
Java9以及以上版本:如果待分配的内存小于1K使用堆内存;待分配的内存大于等于1K使用堆外内存ÿ