【Netty高性能网络框架解析系列】系列文章之四大高性能特性之内存池化技术(3)
netty的内存管理和内存池化设计Netty 内存池设计Netty为什么用内存池化设计Netty管理内存整体架构Jemalloc 内存分片算法和结构内存分配的组件架构图如下Netty分配器类结构层次关系如下PooledByteBufAllocator 分配器Netty 内存池设计Netty为什么用内存池化设计在高性能网络应用中Netty需要频繁地分配和释放内存用于网络数据的读写。主要会产生如下两类问题1.一种JVM管理的内存需要频繁的堆分配导致GC压力大。容易产生频繁的GCGC频繁触发会造成响应时间抖动影响吞吐量和延迟对于低延迟、高并发的网络应用是不可接受的。一种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的内存分配策略。ByteBufAllocatorMetricProviderByteBufAllocatorMetricProvider 是 Netty 框架中用于提供内存分配器性能指标的一个接口。它主要功能是监控和度量 ByteBufAllocator 的内存分配行为帮助开发者分析内存使用情况、优化性能。这里我们主要分析一下分配器等一些逻辑和设计Netty分配器类结构层次关系如下这里介绍几个主要的分配器。后面再根据源码来分析Netty再内存池如何设计的PooledByteBufAllocator它是Netty框架中用于高效内存管理的类。它通过内存池和线程本地缓存来减少内存分配和释放的开销提高性能。该类支持堆内存和直接内存的分配可以根据系统属性进行配置并提供了多种方法来管理和监控内存使用情况。AdaptiveByteBufAllocator这个类是一个自适应性的动态调整内存池分配器适用于Netty框架。它的主要功能是根据配置和系统属性为堆内存和直接内存分配缓冲区并提供了内存使用量的监控接口。通过使用这种分配器可以提高内存分配的效率减少内存碎片同时支持内存泄漏的检测。UnpooledByteBufAllocator:是一个用于分配非池化的字节缓冲区的类它可以根据平台支持情况和用户设置来选择分配堆内存还是直接内存。此外该类还提供了内存使用情况的度量支持能够帮助用户监控内存分配情况。这是 Netty 框架中一种简单的字节缓冲区分配器实现PooledByteBufAllocator 分配器从源码分析static部分 static{int defaultAlignmentSystemPropertyUtil.getInt(io.netty.allocator.directMemoryCacheAlignment,0);int defaultPageSizeSystemPropertyUtil.getInt(io.netty.allocator.pageSize,8192);Throwable pageSizeFallbackCausenull;try{validateAndCalculatePageShifts(defaultPageSize, defaultAlignment);}catch(Throwable t){pageSizeFallbackCauset;defaultPageSize8192;defaultAlignment0;}DEFAULT_PAGE_SIZEdefaultPageSize;DEFAULT_DIRECT_MEMORY_CACHE_ALIGNMENTdefaultAlignment;int defaultMaxOrderSystemPropertyUtil.getInt(io.netty.allocator.maxOrder,9);Throwable maxOrderFallbackCausenull;try{validateAndCalculateChunkSize(DEFAULT_PAGE_SIZE, defaultMaxOrder);}catch(Throwable t){maxOrderFallbackCauset;defaultMaxOrder9;}DEFAULT_MAX_ORDERdefaultMaxOrder;// Determine reasonable defaultfornHeapArena and nDirectArena. // Assuming each arena has3chunks, the pool should not consumemorethan50% of max memory. final Runtime runtimeRuntime.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 defaultMinNumArenaNettyRuntime.availableProcessors()*2;final int defaultChunkSizeDEFAULT_PAGE_SIZEDEFAULT_MAX_ORDER;DEFAULT_NUM_HEAP_ARENAMath.max(0, SystemPropertyUtil.getInt(io.netty.allocator.numHeapArenas,(int)Math.min(defaultMinNumArena, runtime.maxMemory()/ defaultChunkSize /2/3)));DEFAULT_NUM_DIRECT_ARENAMath.max(0, SystemPropertyUtil.getInt(io.netty.allocator.numDirectArenas,(int)Math.min(defaultMinNumArena, PlatformDependent.maxDirectMemory()/ defaultChunkSize /2/3)));// cache sizes DEFAULT_SMALL_CACHE_SIZESystemPropertyUtil.getInt(io.netty.allocator.smallCacheSize,256);DEFAULT_NORMAL_CACHE_SIZESystemPropertyUtil.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 jemallocDEFAULT_MAX_CACHED_BUFFER_CAPACITYSystemPropertyUtil.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_INTERVALSystemPropertyUtil.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_MILLISSystemPropertyUtil.getLong(io.netty.allocator.cacheTrimIntervalMillis,0);}else{DEFAULT_CACHE_TRIM_INTERVAL_MILLISSystemPropertyUtil.getLong(io.netty.allocation.cacheTrimIntervalMillis,0);}}else{DEFAULT_CACHE_TRIM_INTERVAL_MILLISSystemPropertyUtil.getLong(io.netty.allocator.cacheTrimIntervalMillis,0);}DEFAULT_USE_CACHE_FOR_ALL_THREADSSystemPropertyUtil.getBoolean(io.netty.allocator.useCacheForAllThreads,false);DEFAULT_DISABLE_CACHE_FINALIZERS_FOR_FAST_THREAD_LOCAL_THREADSSystemPropertyUtil.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_CHUNKSystemPropertyUtil.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(pageSizeFallbackCausenull){logger.debug(-Dio.netty.allocator.pageSize: {}, DEFAULT_PAGE_SIZE);}else{logger.debug(-Dio.netty.allocator.pageSize: {}, DEFAULT_PAGE_SIZE, pageSizeFallbackCause);}if(maxOrderFallbackCausenull){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_SIZEDEFAULT_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的内存都是按照页内存都方式进行最小化分配。这次分析到这里
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2579133.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!