Netty里的內存管理是通過ByteBuf這個類作為橋梁連接著業(yè)務代碼與jdk底層的內存。所以理解ByteBuf的結構就很有必要了。
ByteBuf
ByteBuf的內部結構如下圖:

ByteBuf類結構圖
ByteBuf分類
- Pooled和Unpooled:pooled類型的bytebuf是在已經申請好的內存塊取一塊內存,而Unpooled是直接通過JDK底層代碼申請。
- Unsafe和非Unsafe:這里的Unsafe是JDK底層的對象,通過它能夠直接操作到內存。
- Heap和Direct:一個是在堆上分配,一個是直接內存。Direct不受GC的控制。
ByteBufAllocator
ByteBuf對象是通過ByteBufAllocator來進行生成的,其中AbstractByteBufAllocator里實現在大部分的功能,具體是pooled還是unpooled類型的byteBuf是留給相應的子類來實現的,而Heap和Direct是通過暴露不同的接口來區(qū)分的,Unsafe與非Unsafe是通過JDK內部的平臺來進行判斷是否能生成Unsafe類的ByteBuf。ByteBufAllocator類圖如下:
ByteBufAllocator類圖
UnpooledByteBufAllocator分配heap內存
-
通過調用heapBuffer方法分配一塊heap內存AbstractByteBufAllocator的heapBuffer方法
-
根據平臺是否支持unsafe操作,生成不同的對象
-
unsafe類的構造過程
-
非unsafe類型的直接調用new byte[]構造
-
unsafe類型的byteBuf申請內存對象
Unsafe與非Unsafe類型的byteBuf內部實現上的差異
-
非unsafe的getByte方法
-
unsafe的getByte方法
image.png
UnpooledByteBufAllocator分配direct內存
-
UnpooledByteBufAllocator類的newDirectBuffer方法
-
UnpooledUnsafeDirectByteBuf創(chuàng)建流程




















