【Netty高性能网络框架解析系列】系列文章之四大高性能特性之内存池化技术(3)
netty的内存管理和内存池化设计
- Netty 内存池设计
- Netty为什么用内存池化设计:
- Netty管理内存整体架构
- Jemalloc 内存分片算法和结构
- 内存分配的组件架构图如下:
- Netty分配器类结构层次关系如下:
- PooledByteBufAllocator 分配器
Netty 内存池设计
Netty为什么用内存池化设计:
在高性能网络应用中,Netty需要频繁地分配和释放内存用于网络数据的读写。
主要会产生如下两类问题:
1.一种JVM管理的内存,需要频繁的堆分配导致GC压力大。容易产生频繁的GC,GC频繁触发会造成响应时间抖动,影响吞吐量和延迟,对于低延迟、高并发的网络应用是不可接受的。
一种DirectBuffer(直接内存/堆外内存),依赖操作系统的分配和回收,管理成本会更高。
2.内存碎片问题:
直接通过Unsafe或者ByteBuffer.allocateDirect频繁的分配内存,容易造成碎片,导致大块连续内存不足。性能不稳定。
那如何解决这两类问题的解决方案
Netty通过内存池复用已分配的内存块,减少分配和回收次数。
对不同大小的内存用不同分配策略
(1)、对小块内存做精细化管理(Tiny/Small)。
(2)、对大块内存做按需分配(Normal/Huge),实现高效的内存使用和低延迟响应。
Netty管理内存整体架构
Jemalloc 内存分片算法和结构
主要特点和优势:
1.线程缓存 (Thread Caches): 每个线程都有自己的缓存,减少了跨线程的内存分配冲突。
2.区域分配 (Arena Allocation): 将内存划分为多个区域(arenas),每个区域独立管理一组内存块,进一步减少锁竞争。
3.延迟释放 (Lazy Free): 延迟释放不再使用的内存,直到下一次内存分配时,减少频繁的内存释放操作。
4.碎片整理 (Fragmentation Reduction): 通过多种策略减少内存碎片,提高内存使用效率。
5.可配置性: 提供了多种配置选项,允许开发者根据应用需求调整内存分配策略。
内存分配的组件架构图如下:
netty整个框架内存设计这块的组件设计如上:
针对架构图中的各个组件进行说明
ResourceLeakDetector:
这个组件主要针对Netty各个组件进行内存检测。 是一个用于检测资源泄漏的工具类,尤其在处理高性能网络应用时,能有效帮助开发者识别未正确释放的资源(如 ByteBuf 等内存资源),从而避免内存溢出(OOM),主要跟踪Netty资源内存的创建和释放等。
ByteBufAllocator:
是一个非常重要的组件,它用于管理内存的分配和释放。Netty使用它来创建各种类型的ByteBuf实例,这些ByteBuf实例用于存储和传输数据。ByteBufAllocator的实现通常依赖于Netty的实现细节,比如它是否使用池化(pooling)或非池化(non-pooling)的内存分配策略。
ByteBufAllocatorMetricProvider:
ByteBufAllocatorMetricProvider 是 Netty 框架中用于提供内存分配器性能指标的一个接口。它主要功能是监控和度量 ByteBufAllocator 的内存分配行为,帮助开发者分析内存使用情况、优化性能。
这里我们主要分析一下分配器等一些逻辑和设计
Netty分配器类结构层次关系如下:
这里介绍几个主要的分配器。后面再根据源码来分析Netty再内存池如何设计的
PooledByteBufAllocator:它是Netty框架中用于高效内存管理的类。它通过内存池和线程本地缓存来减少内存分配和释放的开销,提高性能。该类支持堆内存和直接内存的分配,可以根据系统属性进行配置,并提供了多种方法来管理和监控内存使用情况。
AdaptiveByteBufAllocator:这个类是一个自适应性的动态调整内存池分配器,适用于Netty框架。它的主要功能是根据配置和系统属性为堆内存和直接内存分配缓冲区,并提供了内存使用量的监控接口。通过使用这种分配器,可以提高内存分配的效率,减少内存碎片,同时支持内存泄漏的检测。
UnpooledByteBufAllocator:是一个用于分配非池化的字节缓冲区的类,它可以根据平台支持情况和用户设置来选择分配堆内存还是直接内存。此外,该类还提供了内存使用情况的度量支持,能够帮助用户监控内存分配情况。这是 Netty 框架中一种简单的字节缓冲区分配器实现
PooledByteBufAllocator 分配器
从源码分析
static部分 :
static{int defaultAlignment=SystemPropertyUtil.getInt("io.netty.allocator.directMemoryCacheAlignment",0);int defaultPageSize=SystemPropertyUtil.getInt("io.netty.allocator.pageSize",8192);Throwable pageSizeFallbackCause=null;try{validateAndCalculatePageShifts(defaultPageSize, defaultAlignment);}catch(Throwable t){pageSizeFallbackCause=t;defaultPageSize=8192;defaultAlignment=0;}DEFAULT_PAGE_SIZE=defaultPageSize;DEFAULT_DIRECT_MEMORY_CACHE_ALIGNMENT=defaultAlignment;int defaultMaxOrder=SystemPropertyUtil.getInt("io.netty.allocator.maxOrder",9);Throwable maxOrderFallbackCause=null;try{validateAndCalculateChunkSize(DEFAULT_PAGE_SIZE, defaultMaxOrder);}catch(Throwable t){maxOrderFallbackCause=t;defaultMaxOrder=9;}DEFAULT_MAX_ORDER=defaultMaxOrder;// Determine reasonable defaultfornHeapArena and nDirectArena. // Assuming each arena has3chunks, the pool should not consumemorethan50% of max memory. final Runtime runtime=Runtime.getRuntime();/* * We use2* available processors by default to reduce contention as we use2* available processorsforthe * number of EventLoopsinNIO and EPOLL as well. If we choose a smaller number we will run into hot spots as * allocation and de-allocation needs to be synchronized on the PoolArena. * * See https://github.com/netty/netty/issues/3888. */ final int defaultMinNumArena=NettyRuntime.availableProcessors()*2;final int defaultChunkSize=DEFAULT_PAGE_SIZE<<DEFAULT_MAX_ORDER;DEFAULT_NUM_HEAP_ARENA=Math.max(0, SystemPropertyUtil.getInt("io.netty.allocator.numHeapArenas",(int)Math.min(defaultMinNumArena, runtime.maxMemory()/ defaultChunkSize /2/3)));DEFAULT_NUM_DIRECT_ARENA=Math.max(0, SystemPropertyUtil.getInt("io.netty.allocator.numDirectArenas",(int)Math.min(defaultMinNumArena, PlatformDependent.maxDirectMemory()/ defaultChunkSize /2/3)));// cache sizes DEFAULT_SMALL_CACHE_SIZE=SystemPropertyUtil.getInt("io.netty.allocator.smallCacheSize",256);DEFAULT_NORMAL_CACHE_SIZE=SystemPropertyUtil.getInt("io.netty.allocator.normalCacheSize",64);//32kb is the default maximum capacity of the cached buffer. Similar to what is explainedin//'Scalable memory allocation using jemalloc'DEFAULT_MAX_CACHED_BUFFER_CAPACITY=SystemPropertyUtil.getInt("io.netty.allocator.maxCachedBufferCapacity",32*1024);// the number of threshold of allocations when cached entries will be freed upifnot frequently used DEFAULT_CACHE_TRIM_INTERVAL=SystemPropertyUtil.getInt("io.netty.allocator.cacheTrimInterval",8192);if(SystemPropertyUtil.contains("io.netty.allocation.cacheTrimIntervalMillis")){logger.warn("-Dio.netty.allocation.cacheTrimIntervalMillis is deprecated,"+" use -Dio.netty.allocator.cacheTrimIntervalMillis");if(SystemPropertyUtil.contains("io.netty.allocator.cacheTrimIntervalMillis")){// Both system properties are specified. Use the non-deprecated one. DEFAULT_CACHE_TRIM_INTERVAL_MILLIS=SystemPropertyUtil.getLong("io.netty.allocator.cacheTrimIntervalMillis",0);}else{DEFAULT_CACHE_TRIM_INTERVAL_MILLIS=SystemPropertyUtil.getLong("io.netty.allocation.cacheTrimIntervalMillis",0);}}else{DEFAULT_CACHE_TRIM_INTERVAL_MILLIS=SystemPropertyUtil.getLong("io.netty.allocator.cacheTrimIntervalMillis",0);}DEFAULT_USE_CACHE_FOR_ALL_THREADS=SystemPropertyUtil.getBoolean("io.netty.allocator.useCacheForAllThreads",false);DEFAULT_DISABLE_CACHE_FINALIZERS_FOR_FAST_THREAD_LOCAL_THREADS=SystemPropertyUtil.getBoolean("io.netty.allocator.disableCacheFinalizersForFastThreadLocalThreads",false);// Use1023by default as we use an ArrayDeque as backing storagewhichwillthenallocate an internal array // of1024elements. Otherwise we would allocate2048and only use1024whichis wasteful. DEFAULT_MAX_CACHED_BYTEBUFFERS_PER_CHUNK=SystemPropertyUtil.getInt("io.netty.allocator.maxCachedByteBuffersPerChunk",1023);if(logger.isDebugEnabled()){logger.debug("-Dio.netty.allocator.numHeapArenas: {}", DEFAULT_NUM_HEAP_ARENA);logger.debug("-Dio.netty.allocator.numDirectArenas: {}", DEFAULT_NUM_DIRECT_ARENA);if(pageSizeFallbackCause==null){logger.debug("-Dio.netty.allocator.pageSize: {}", DEFAULT_PAGE_SIZE);}else{logger.debug("-Dio.netty.allocator.pageSize: {}", DEFAULT_PAGE_SIZE, pageSizeFallbackCause);}if(maxOrderFallbackCause==null){logger.debug("-Dio.netty.allocator.maxOrder: {}", DEFAULT_MAX_ORDER);}else{logger.debug("-Dio.netty.allocator.maxOrder: {}", DEFAULT_MAX_ORDER, maxOrderFallbackCause);}logger.debug("-Dio.netty.allocator.chunkSize: {}", DEFAULT_PAGE_SIZE<<DEFAULT_MAX_ORDER);logger.debug("-Dio.netty.allocator.smallCacheSize: {}", DEFAULT_SMALL_CACHE_SIZE);logger.debug("-Dio.netty.allocator.normalCacheSize: {}", DEFAULT_NORMAL_CACHE_SIZE);logger.debug("-Dio.netty.allocator.maxCachedBufferCapacity: {}", DEFAULT_MAX_CACHED_BUFFER_CAPACITY);logger.debug("-Dio.netty.allocator.cacheTrimInterval: {}", DEFAULT_CACHE_TRIM_INTERVAL);logger.debug("-Dio.netty.allocator.cacheTrimIntervalMillis: {}", DEFAULT_CACHE_TRIM_INTERVAL_MILLIS);logger.debug("-Dio.netty.allocator.useCacheForAllThreads: {}", DEFAULT_USE_CACHE_FOR_ALL_THREADS);logger.debug("-Dio.netty.allocator.maxCachedByteBuffersPerChunk: {}", DEFAULT_MAX_CACHED_BYTEBUFFERS_PER_CHUNK);logger.debug("-Dio.netty.allocator.disableCacheFinalizersForFastThreadLocalThreads: {}", DEFAULT_DISABLE_CACHE_FINALIZERS_FOR_FAST_THREAD_LOCAL_THREADS);}}这部分代码的逻辑主要是初始化一些参数
1、配置里面或者模式的页内存大小,块内存大小,以及内存偏移量
2、堆内存和直接内存按照块内存大小分多少个块内存数,netty的内存都是按照页内存都方式进行最小化分配。
这次分析到这里
