網站首頁 編程語言 正文
Compiler
Compiler 就是 JIT 編譯器線程在編譯 code 時本身所使用的內存。
查看 NMT 詳情:
[0x0000ffff93e3acc0] Thread::allocate(unsigned long, bool, MemoryType)+0x348 [0x0000ffff9377a498] CompileBroker::make_compiler_thread(char const*, CompileQueue*, CompilerCounters*, AbstractCompiler*, Thread*)+0x120 [0x0000ffff9377ce98] CompileBroker::init_compiler_threads(int, int)+0x148 [0x0000ffff9377d400] CompileBroker::compilation_init()+0xc8 (malloc=37KB type=Thread #12)
跟蹤調用鏈路:
InitializeJVM ->Threads::create_vm ->CompileBroker::compilation_init ->CompileBroker::init_compiler_threads ->CompileBroker::make_compiler_thread
發現最后 make_compiler_thread 的線程的個數是在 compilation_init() 中計算的:
# hotspot/src/share/vm/compiler/CompileBroker.cpp void CompileBroker::compilation_init() { ...... // No need to initialize compilation system if we do not use it. if (!UseCompiler) { return; } #ifndef SHARK // Set the interface to the current compiler(s). int c1_count = CompilationPolicy::policy()->compiler_count(CompLevel_simple); int c2_count = CompilationPolicy::policy()->compiler_count(CompLevel_full_optimization); ...... // Start the CompilerThreads init_compiler_threads(c1_count, c2_count); ...... }
追溯 c1_count、c2_count 的計算邏輯,首先在 JVM 初始化的時候(Threads::create_vm -> init_globals -> compilationPolicy_init)要設置編譯的策略 CompilationPolicy:
# hotspot/src/share/vm/runtime/arguments.cpp void Arguments::set_tiered_flags() { // With tiered, set default policy to AdvancedThresholdPolicy, which is 3. if (FLAG_IS_DEFAULT(CompilationPolicyChoice)) { FLAG_SET_DEFAULT(CompilationPolicyChoice, 3); } ...... } # hotspot/src/share/vm/runtime/compilationPolicy.cpp // Determine compilation policy based on command line argument void compilationPolicy_init() { CompilationPolicy::set_in_vm_startup(DelayCompilationDuringStartup); switch(CompilationPolicyChoice) { ...... case 3: #ifdef TIERED CompilationPolicy::set_policy(new AdvancedThresholdPolicy()); #else Unimplemented(); #endif break; ...... CompilationPolicy::policy()->initialize(); }
此時我們默認開啟了分層編譯,所以 CompilationPolicyChoice 為 3 ,編譯策略選用的是 AdvancedThresholdPolicy,查看相關源碼(compilationPolicy_init -> AdvancedThresholdPolicy::initialize):
# hotspot/src/share/vm/runtime/advancedThresholdPolicy.cpp void AdvancedThresholdPolicy::initialize() { // Turn on ergonomic compiler count selection if (FLAG_IS_DEFAULT(CICompilerCountPerCPU) && FLAG_IS_DEFAULT(CICompilerCount)) { FLAG_SET_DEFAULT(CICompilerCountPerCPU, true); } int count = CICompilerCount; if (CICompilerCountPerCPU) { // Simple log n seems to grow too slowly for tiered, try something faster: log n * log log n int log_cpu = log2_int(os::active_processor_count()); int loglog_cpu = log2_int(MAX2(log_cpu, 1)); count = MAX2(log_cpu * loglog_cpu, 1) * 3 / 2; } set_c1_count(MAX2(count / 3, 1)); set_c2_count(MAX2(count - c1_count(), 1)); ...... }
我們可以發現,在未手動設置 -XX:CICompilerCountPerCPU 和 -XX:CICompilerCount 這兩個參數的時候,JVM 會啟動 CICompilerCountPerCPU ,啟動編譯線程的數目會根據 CPU 數重新計算而不再使用默認的 CICompilerCount 的值(3),計算公式通常情況下為 log n * log log n * 1.5(log 以 2 為底),此時筆者使用的機器有 64 個 CPU,經過計算得出編譯線程的數目為 18。計算出編譯線程的總數目之后,再按 1:2 的比例分別分配給 C1、C2,即我們上文所求的 c1_count、c2_count。
使用 jinfo -flag CICompilerCount 來驗證此時 JVM 進程的編譯線程數目:
jinfo -flag CICompilerCount -XX:CICompilerCount=18
所以我們可以通過顯式的設置 -XX:CICompilerCount 來控制 JVM 開啟編譯線程的數目,從而限制 Compiler 部分所使用的內存(當然這部分內存比較小)。
我們還可以通過 -XX:-TieredCompilation 關閉分層編譯來降低內存使用,當然是否關閉分層編譯取決于實際的業務需求,節省的這點內存實在微乎其微。
編譯線程也是線程,所以我們還可以通過 -XX:VMThreadStackSize 設置一個更小的值來節省此部分內存,但是削減虛擬機線程的堆棧大小是危險的操作,并不建議去因為此設置這個參數。
Internal
Internal 包含命令行解析器使用的內存、JVMTI、PerfData 以及 Unsafe 分配的內存等等。
其中命令行解釋器就是在初始化創建虛擬機時對 JVM 的命令行參數加以解析并執行相應的操作,如對參數 -XX:NativeMemoryTracking=detail
進行解析。
JVMTI(JVM Tool Interface)是開發和監視 JVM 所使用的編程接口。它提供了一些方法去檢查 JVM 狀態和控制 JVM 的運行,詳情可以查看 JVMTI官方文檔 [1]。
PerfData 是 JVM 中用來記錄一些指標數據的文件,如果開啟 -XX:+UsePerfData(默認開啟),JVM 會通過 mmap 的方式(即使用上文中提到的 os::reserve_memory 和 os::commit_memory)去映射到 {tmpdir}/hsperfdata_/pid
文件中,jstat 通過讀取 PerfData 中的數據來展示 JVM 進程中的各種指標信息.
需要注意的是, {tmpdir}/hsperfdata_/pid
與{tmpdir}/.java_pid
并不是一個東西,后者是在 Attach 機制中用來通訊的,類似一種 Unix Domain Socket 的思想,不過真正的 Unix Domain Socket(JEP380 [2])在 JDK16 中才支持。
我們在操作 nio 時經常使用 ByteBuffer ,其中 ByteBuffer.allocateDirect / DirectByteBuffer 會通過 unsafe.allocateMemory 的方式來 malloc 分配 naive memory,雖然 DirectByteBuffer 本身還是存放于 Heap 堆中,但是它對應的 address 映射的卻是分配在堆外內存的 native memory,NMT 會將 Unsafe_AllocateMemory 方式分配的內存記錄在 Internal 之中(jstat 也是通過 ByteBuffer 的方式來使用 PerfData)。
需要注意的是,Unsafe_AllocateMemory 分配的內存在 JDK11之前,在 NMT 中都屬于 Internal,但是在 JDK11 之后被 NMT 歸屬到 Other 中。
例如相同 ByteBuffer.allocateDirect 在 JDK11 中進行追蹤:[0x0000ffff8c0b4a60] Unsafe_AllocateMemory0+0x60``[0x0000ffff6b822fbc] (malloc=393218KB type=Other #3)
簡單查看下相關源碼:
# ByteBuffer.java public static ByteBuffer allocateDirect(int capacity) { return new DirectByteBuffer(capacity); } # DirectByteBuffer.java DirectByteBuffer(int cap) { // package-private ...... long base = 0; try { base = unsafe.allocateMemory(size); } ...... # Unsafe.java public native long allocateMemory(long bytes); # hotspot/src/share/vm/prims/unsafe.cpp UNSAFE_ENTRY(jlong, Unsafe_AllocateMemory(JNIEnv *env, jobject unsafe, jlong size)) UnsafeWrapper("Unsafe_AllocateMemory"); size_t sz = (size_t)size; ...... sz = round_to(sz, HeapWordSize); void* x = os::malloc(sz, mtInternal); ...... UNSAFE_END
一般情況下,命令行解釋器、JVMTI等方式不會申請太大的內存,我們需要注意的是通過 Unsafe_AllocateMemory 方式申請的堆外內存(如業務使用了 Netty ),可以通過一個簡單的示例來進行驗證
這個示例的 JVM 啟動參數為:-Xmx1G -Xms1G -XX:+UseG1GC -XX:MaxMetaspaceSize=256M -XX:ReservedCodeCacheSize=256M -XX:NativeMemoryTracking=detail(去除了 -XX:MaxDirectMemorySize=256M 的限制):
import java.nio.ByteBuffer; public class ByteBufferTest { private static int _1M = 1024 * 1024; private static ByteBuffer allocateBuffer_1 = ByteBuffer.allocateDirect(128 * _1M); private static ByteBuffer allocateBuffer_2 = ByteBuffer.allocateDirect(256 * _1M); public static void main(String[] args) throws Exception { System.out.println("MaxDirect memory: " + sun.misc.VM.maxDirectMemory() + " bytes"); System.out.println("Direct allocation: " + (allocateBuffer_1.capacity() + allocateBuffer_2.capacity()) + " bytes"); System.out.println("Native memory used: " + sun.misc.SharedSecrets.getJavaNioAccess().getDirectBufferPool().getMemoryUsed() + " bytes"); Thread.sleep(6000000); } }
查看輸出:
MaxDirect memory: 1073741824 bytes
Direct allocation: 402653184 bytes
Native memory used: 402653184 bytes
查看 NMT 詳情:
- Internal (reserved=405202KB, committed=405202KB) (malloc=405170KB #3605) (mmap: reserved=32KB, committed=32KB) ...... [0x0000ffffbb599190] Unsafe_AllocateMemory+0x1c0 [0x0000ffffa40157a8] (malloc=393216KB type=Internal #2) ...... [0x0000ffffbb04b3f8] GenericGrowableArray::raw_allocate(int)+0x188 [0x0000ffffbb4339d8] PerfDataManager::add_item(PerfData*, bool) [clone .constprop.16]+0x108 [0x0000ffffbb434118] PerfDataManager::create_string_variable(CounterNS, char const*, int, char const*, Thread*)+0x178 [0x0000ffffbae9d400] CompilerCounters::CompilerCounters(char const*, int, Thread*) [clone .part.78]+0xb0 (malloc=3KB type=Internal #1) ......
可以發現,我們在代碼中使用 ByteBuffer.allocateDirect(內部也是使用 new DirectByteBuffer(capacity))的方式,即 Unsafe_AllocateMemory 申請的堆外內存被 NMT 以 Internal 的方式記錄了下來:(128 M + 256 M)= 384 M = 393216 KB = 402653184 Bytes。
當然我們可以使用參數 -XX:MaxDirectMemorySize 來限制 Direct Buffer 申請的最大內存。
Symbol
Symbol 為 JVM 中的符號表所使用的內存,HotSpot中符號表主要有兩種:SymbolTable 與 StringTable。
大家都知道 Java 的類在編譯之后會生成 Constant pool 常量池,常量池中會有很多的字符串常量,HotSpot 出于節省內存的考慮,往往會將這些字符串常量作為一個 Symbol 對象存入一個 HashTable 的表結構中即 SymbolTable,如果該字符串可以在 SymbolTable 中 lookup(SymbolTable::lookup)到,那么就會重用該字符串,如果找不到才會創建新的 Symbol(SymbolTable::new_symbol)。
當然除了 SymbolTable,還有它的雙胞胎兄弟 StringTable(StringTable 結構與 SymbolTable 基本是一致的,都是 HashTable 的結構),即我們常說的字符串常量池。平時做業務開發和 StringTable 打交道會更多一些,HotSpot 也是基于節省內存的考慮為我們提供了 StringTable,我們可以通過 String.intern 的方式將字符串放入 StringTable 中來重用字符串。
編寫一個簡單的示例:
public class StringTableTest { public static void main(String[] args) throws Exception { while (true){ String str = new String("StringTestData_" + System.currentTimeMillis()); str.intern(); } } }
啟動程序后我們可以使用 jcmd VM.native_memory baseline
來創建一個基線方便對比,稍作等待后再使用 jcmd VM.native_memory summary.diff/detail.diff
與創建的基線作對比,對比后我們可以發現:
Total: reserved=2831553KB +20095KB, committed=1515457KB +20095KB ...... - Symbol (reserved=18991KB +17144KB, committed=18991KB +17144KB) (malloc=18504KB +17144KB #2307 +2143) (arena=488KB #1) ...... [0x0000ffffa2aef4a8] BasicHashtable<(MemoryType)9>::new_entry(unsigned int)+0x1a0 [0x0000ffffa2aef558] Hashtable::new_entry(unsigned int, oopDesc*)+0x28 [0x0000ffffa2fbff78] StringTable::basic_add(int, Handle, unsigned short*, int, unsigned int, Thread*)+0xe0 [0x0000ffffa2fc0548] StringTable::intern(Handle, unsigned short*, int, Thread*)+0x1a0 (malloc=17592KB type=Symbol +17144KB #2199 +2143) ......
JVM 進程這段時間內存一共增長了 20095KB,其中絕大部分都是 Symbol 申請的內存(17144KB),查看具體的申請信息正是 StringTable::intern 在不斷的申請內存。
如果我們的程序錯誤的使用 String.intern() 或者 JDK intern 相關 BUG 導致了內存異常,可以通過這種方式輕松協助定位出來。
需要注意的是,虛擬機提供的參數 -XX:StringTableSize 并不是來限制 StringTable 最大申請的內存大小的,而是用來限制 StringTable 的表的長度的,我們加上 -XX:StringTableSize=10M
來重新啟動 JVM 進程,一段時間后查看 NMT 追蹤情況:
- Symbol (reserved=100859KB +17416KB, committed=100859KB +17416KB) (malloc=100371KB +17416KB #2359 +2177) (arena=488KB #1) ...... [0x0000ffffa30c14a8] BasicHashtable<(MemoryType)9>::new_entry(unsigned int)+0x1a0 [0x0000ffffa30c1558] Hashtable::new_entry(unsigned int, oopDesc*)+0x28 [0x0000ffffa3591f78] StringTable::basic_add(int, Handle, unsigned short*, int, unsigned int, Thread*)+0xe0 [0x0000ffffa3592548] StringTable::intern(Handle, unsigned short*, int, Thread*)+0x1a0 (malloc=18008KB type=Symbol +17416KB #2251 +2177)
可以發現 StringTable 的大小是超過 10M 的,查看該參數的作用:
# hotsopt/src/share/vm/classfile/symnolTable.hpp StringTable() : RehashableHashtable((int)StringTableSize, sizeof (HashtableEntry)) {} StringTable(HashtableBucket* t, int number_of_entries) : RehashableHashtable((int)StringTableSize, sizeof (HashtableEntry), t, number_of_entries) {}
因為 StringTable 在 HotSpot 中是以 HashTable 的形式存儲的,所以 -XX:StringTableSize 參數設置的其實是 HashTable 的長度,如果該值設置的過小的話,即使 HashTable 進行 rehash,hash 沖突也會十分頻繁,會造成性能劣化并有可能導致進入 SafePoint 的時間增長。如果發生這種情況,可以調大該值。
- -XX:StringTableSize 在 32 位系統默認為 1009、64 位默認為 60013 :
const int defaultStringTableSize = NOT_LP64(1009) LP64_ONLY(60013);
。 - G1中可以使用 -XX:+UseStringDeduplication 參數來開啟字符串自動去重功能(默認關閉),并使用 -XX:StringDeduplicationAgeThreshold 來控制字符串參與去重的 GC 年齡閾值。
- 與 -XX:StringTableSize 同理,我們可以通過 -XX:SymbolTableSize 來控制 SymbolTable 表的長度。
如果我們使用的是 JDK11 之后的 NMT,我們可以直接通過命令 jcmd VM.stringtable
與 jcmd VM.symboltable
來查看兩者的使用情況:
StringTable statistics: Number of buckets : 16777216 = 134217728 bytes, each 8 Number of entries : 39703 = 635248 bytes, each 16 Number of literals : 39703 = 2849304 bytes, avg 71.765 Total footprsize_t : = 137702280 bytes Average bucket size : 0.002 Variance of bucket size : 0.002 Std. dev. of bucket size: 0.049 Maximum bucket size : 2 SymbolTable statistics: Number of buckets : 20011 = 160088 bytes, each 8 Number of entries : 20133 = 483192 bytes, each 24 Number of literals : 20133 = 753832 bytes, avg 37.443 Total footprint : = 1397112 bytes Average bucket size : 1.006 Variance of bucket size : 1.013 Std. dev. of bucket size: 1.006 Maximum bucket size : 9
Native Memory Tracking
Native Memory Tracking 使用的內存就是 JVM 進程開啟 NMT 功能后,NMT 功能自身所申請的內存。
查看源碼會發現,JVM 會在 MemTracker::init() 初始化的時候,使用 tracking_level() -> init_tracking_level() 獲取我們設定的 tracking_level 追蹤等級(如:summary、detail),然后將獲取到的 level 分別傳入 MallocTracker::initialize(level) 與 VirtualMemoryTracker::initialize(level) 進行判斷,只有 level >= summary 的情況下,虛擬機才會分配 NMT 自身所用到的內存,如:VirtualMemoryTracker、MallocMemorySummary、MallocSiteTable(detail 時才會創建) 等來記錄 NMT 追蹤的各種數據。
# /hotspot/src/share/vm/services/memTracker.cpp void MemTracker::init() { NMT_TrackingLevel level = tracking_level(); ...... } # /hotspot/src/share/vm/services/memTracker.hpp static inline NMT_TrackingLevel tracking_level() { if (_tracking_level == NMT_unknown) { // No fencing is needed here, since JVM is in single-threaded // mode. _tracking_level = init_tracking_level(); _cmdline_tracking_level = _tracking_level; } return _tracking_level; } # /hotspot/src/share/vm/services/memTracker.cpp NMT_TrackingLevel MemTracker::init_tracking_level() { NMT_TrackingLevel level = NMT_off; ...... if (os::getenv(buf, nmt_option, sizeof(nmt_option))) { if (strcmp(nmt_option, "summary") == 0) { level = NMT_summary; } else if (strcmp(nmt_option, "detail") == 0) { #if PLATFORM_NATIVE_STACK_WALKING_SUPPORTED level = NMT_detail; #else level = NMT_summary; #endif // PLATFORM_NATIVE_STACK_WALKING_SUPPORTED } ...... } ...... if (!MallocTracker::initialize(level) || !VirtualMemoryTracker::initialize(level)) { level = NMT_off; } return level; } # /hotspot/src/share/vm/services/memTracker.cpp bool MallocTracker::initialize(NMT_TrackingLevel level) { if (level >= NMT_summary) { MallocMemorySummary::initialize(); } if (level == NMT_detail) { return MallocSiteTable::initialize(); } return true; } void MallocMemorySummary::initialize() { assert(sizeof(_snapshot) >= sizeof(MallocMemorySnapshot), "Sanity Check"); // Uses placement new operator to initialize static area. ::new ((void*)_snapshot)MallocMemorySnapshot(); } # bool VirtualMemoryTracker::initialize(NMT_TrackingLevel level) { if (level >= NMT_summary) { VirtualMemorySummary::initialize(); } return true; }
我們執行的 jcmd VM.native_memory summary/detail
命令,就會使用 NMTDCmd::report 方法來根據等級的不同獲取不同的數據:
summary 時使用 MemSummaryReporter::report() 獲取 VirtualMemoryTracker、MallocMemorySummary 等儲存的數據;
detail 時使用 MemDetailReporter::report() 獲取 VirtualMemoryTracker、MallocMemorySummary、MallocSiteTable 等儲存的數據。
hotspot/src/share/vm/services/nmtDCmd.cpp
void NMTDCmd::execute(DCmdSource source, TRAPS) { ...... if (_summary.value()) { report(true, scale_unit); } else if (_detail.value()) { if (!check_detail_tracking_level(output())) { return; } report(false, scale_unit); } ...... }
void NMTDCmd::report(bool summaryOnly, size_t scale_unit) { MemBaseline baseline; if (baseline.baseline(summaryOnly)) { if (summaryOnly) { MemSummaryReporter rpt(baseline, output(), scale_unit); rpt.report(); } else { MemDetailReporter rpt(baseline, output(), scale_unit); rpt.report(); } } }
一般 NMT 自身占用的內存是比較小的,不需要太過關心。
Arena Chunk
Arena 是 JVM 分配的一些 Chunk(內存塊),當退出作用域或離開代碼區域時,內存將從這些 Chunk 中釋放出來。然后這些 Chunk 就可以在其他子系統中重用. 需要注意的是,此時統計的 Arena 與 Chunk ,是 HotSpot 自己定義的 Arena、Chunk,而不是 Glibc 中相關的 Arena 與 Chunk 的概念。
我們會發現 NMT 詳情中會有很多關于 Arena Chunk 的分配信息都是:
[0x0000ffff935906e0] ChunkPool::allocate(unsigned long, AllocFailStrategy::AllocFailEnum)+0x158 [0x0000ffff9358ec14] Arena::Arena(MemoryType, unsigned long)+0x18c ......
JVM 中通過 ChunkPool 來管理重用這些 Chunk,比如我們在創建線程時:
# /hotspot/src/share/vm/runtime/thread.cpp Thread::Thread() { ...... set_resource_area(new (mtThread)ResourceArea()); ...... set_handle_area(new (mtThread) HandleArea(NULL)); ......
其中 ResourceArea 屬于給線程分配的一個資源空間,一般 ResourceObj 都存放于此(如 C1/C2 優化時需要訪問的運行時信息);HandleArea 則用來存放線程所持有的句柄(handle),使用句柄來關聯使用的對象。這兩者都會去申請 Arena,而 Arena 則會通過 ChunkPool::allocate 來申請一個新的 Chunk 內存塊。除此之外,JVM 進程用到 Arena 的地方還有非常多,比如 JMX、OopMap 等等一些相關的操作都會用到 ChunkPool。
眼尖的讀者可能會注意到上文中提到,通常情況下會通過 ChunkPool::allocate 的方式來申請 Chunk 內存塊。是的,其實除了 ChunkPool::allocate 的方式, JVM 中還存在另外一種申請 Arena Chunk 的方式,即直接借助 Glibc 的 malloc 來申請內存,JVM 為我們提供了相關的控制參數 UseMallocOnly:
develop(bool, UseMallocOnly, false, \ "Use only malloc/free for allocation (no resource area/arena)")
我們可以發現這個參數是一個 develop 的參數,一般情況下我們是使用不到的,因為 VM option 'UseMallocOnly' is develop and is available only in debug version of VM,即我們只能在 debug 版本的 JVM 中才能開啟該參數。
這里有的讀者可能會有一個疑問,即是不是可以通過使用參數 -XX:+IgnoreUnrecognizedVMOptions(該參數開啟之后可以允許 JVM 使用一些在 release 版本中不被允許使用的參數)的方式,在正常 release 版本的 JVM 中使用 UseMallocOnly 參數,很遺憾雖然我們可以通過這種方式開啟 UseMallocOnly,但是實際上 UseMallocOnly 卻不會生效,因為在源碼中其邏輯如下:
# hotspot/src/share/vm/memory/allocation.hpp void* Amalloc(size_t x, AllocFailType alloc_failmode = AllocFailStrategy::EXIT_OOM) { assert(is_power_of_2(ARENA_AMALLOC_ALIGNMENT) , "should be a power of 2"); x = ARENA_ALIGN(x); //debug 版本限制 debug_only(if (UseMallocOnly) return malloc(x);) if (!check_for_overflow(x, "Arena::Amalloc", alloc_failmode)) return NULL; NOT_PRODUCT(inc_bytes_allocated(x);) if (_hwm + x > _max) { return grow(x, alloc_failmode); } else { char *old = _hwm; _hwm += x; return old; } }
可以發現,即使我們成功開啟了 UseMallocOnly,也只有在 debug 版本(debug_only
)的 JVM 中才能使用 malloc 的方式分配內存。
我們可以對比下,使用正常版本(release)的 JVM 添加 -XX:+IgnoreUnrecognizedVMOptions -XX:+UseMallocOnly
啟動參數的 NMT 相關日志與使用 debug(fastdebug/slowdebug)版本的 JVM 添加 -XX:+UseMallocOnly
啟動參數的 NMT 相關日志:
# 正常 JVM ,啟動參數添加:-XX:+IgnoreUnrecognizedVMOptions -XX:+UseMallocOnly ...... [0x0000ffffb7d16968] ChunkPool::allocate(unsigned long, AllocFailStrategy::AllocFailEnum)+0x158 [0x0000ffffb7d15f58] Arena::grow(unsigned long, AllocFailStrategy::AllocFailEnum)+0x50 [0x0000ffffb7fc4888] Dict::Dict(int (*)(void const*, void const*), int (*)(void const*), Arena*, int)+0x138 [0x0000ffffb85e5968] Type::Initialize_shared(Compile*)+0xb0 (malloc=32KB type=Arena Chunk #1) ...... # debug版本 JVM ,啟動參數添加:-XX:+UseMallocOnly ...... [0x0000ffff8dfae910] Arena::malloc(unsigned long)+0x74 [0x0000ffff8e2cb3b8] Arena::Amalloc_4(unsigned long, AllocFailStrategy::AllocFailEnum)+0x70 [0x0000ffff8e2c9d5c] Dict::Dict(int (*)(void const*, void const*), int (*)(void const*), Arena*, int)+0x19c [0x0000ffff8e97c3d0] Type::Initialize_shared(Compile*)+0x9c (malloc=5KB type=Arena Chunk #1) ......
我們可以清晰地觀察到調用鏈的不同,即前者還是使用 ChunkPool::allocate 的方式來申請內存,而后者則使用 Arena::malloc 的方式來申請內存,查看 Arena::malloc 代碼:
# hotspot/src/share/vm/memory/allocation.cpp void* Arena::malloc(size_t size) { assert(UseMallocOnly, "shouldn't call"); // use malloc, but save pointer in res. area for later freeing char** save = (char**)internal_malloc_4(sizeof(char*)); return (*save = (char*)os::malloc(size, mtChunk)); }
可以發現代碼中通過 os::malloc
的方式來分配內存,同理釋放內存時直接通過 os::free
即可,如 UseMallocOnly 中釋放內存的相關代碼:
# hotspot/src/share/vm/memory/allocation.cpp // debugging code inline void Arena::free_all(char** start, char** end) { for (char** p = start; p < end; p++) if (*p) os::free(*p); }
雖然 JVM 為我們提供了兩種方式來管理 Arena Chunk 的內存:
- 通過 ChunkPool 池化交由 JVM 自己管理;
- 直接通過 Glibc 的 malloc/free 來進行管理。
但是通常意義下我們只會用到第一種方式,并且一般 ChunkPool 管理的對象都比較小,整體來看 Arena Chunk 這塊內存的使用不會很多。
Unknown
Unknown 則是下面幾種情況
- 當內存類別無法確定時;
- 當 Arena 用作堆棧或值對象時;
- 當類型信息尚未到達時。
NMT 無法追蹤的內存
需要注意的是,NMT 只能跟蹤 JVM 代碼的內存分配情況,對于非 JVM 的內存分配是無法追蹤到的。
- 使用 JNI 調用的一些第三方 native code 申請的內存,比如使用 System.Loadlibrary 加載的一些庫。
- 標準的 Java Class Library,典型的,如文件流等相關操作(如:Files.list、ZipInputStream 和 DirectoryStream 等)。
可以使用操作系統的內存工具等協助排查,或者使用 LD_PRELOAD malloc 函數的 hook/jemalloc/google-perftools(tcmalloc) 來代替 Glibc 的 malloc,協助追蹤內存的分配。
由于篇幅有限,將在下篇文章給大家分享“使用 NMT 協助排查內存問題的案例”,敬請期待!
參考
docs.oracle.com/javase/8/do…
openjdk.org/jeps/380
原文鏈接:https://juejin.cn/post/7167189914457473054
相關推薦
- 2023-04-06 python判斷列表為空的三種方法總結_python
- 2022-06-01 c++深入淺出講解堆排序和堆_C 語言
- 2022-04-30 python的正則表達式和re模塊詳解_python
- 2022-05-06 nginx?負載均衡輪詢方式配置詳解_nginx
- 2022-06-16 Python數據結構之遞歸可視化詳解_python
- 2022-09-12 cmd設置路由route的方法步驟_DOS/BAT
- 2022-05-29 C#中使用HttpPost調用WebService的方法_C#教程
- 2022-03-16 C++中的Lambda函數詳解_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支