目录
一、Heap内存
1、查看Heap内存配置的最大值
Runtime.getRuntime().maxMemory()
2、配置Heap内存最大值的方式
–Xmx<size>
3、配置Heap内存最小值的方式
–Xms<size>
4、查看已使用Heap内存的方式
Runtime.getRuntime().totalMemory()
5、查看未使用Heap内存的方式
Runtime.getRuntime().freeMemory()
二、Direct内存
1、查看Direct内存配置的最大值
sun.misc.VM.maxDirectMemory()
如果在启动参数中配置了-XX:MaxDirectMemorySize,则可以通过以下命令查看
jcmd <pid> VM.comand_line
或
jcmd <pid> VM.flags
2、配置Direct内存最大值的方式
使用JVM参数进行配置
-XX:MaxDirectMemorySize=<size>
若未使用上述JVM参数,会采用与下述JVM参数相同的值
–Xmx<size>
若上述2个JVM参数都没配置,则其值会与如下API获取的值一致
Runtime.getRuntime().maxMemory()
3、获取Direct内存已使用大小
方法一:
sun.misc.SharedSecrets.getJavaNioAccess().getDirectBufferPool().getMemoryUsed()
方法二:
List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
for (BufferPoolMXBean pool : pools) {
System.out.println(pool.getName());
System.out.println(pool.getCount());
System.out.println(pool.getMemoryUsed());
System.out.println(pool.getTotalCapacity());
System.out.println("----------");
}
输出结果:
direct
1
1025
1025
-----------------
mapped
0
0
0
方法三:
使用jconsole
三、常用内存区域的配置参数
## heap
-Xms=<n> and -Xmx=<n>
-XX:NewRatio## Metaspace
since JDK8.0
-XX:MetaspaceSize and -XX:MaxMetaspaceSize
before JDK8.0
-XX:PermSize and -XX:MaxPermSize## Threads
-Xss=<size>
-XX:ThreadStackSize=<size>## Code Cache
-XX:InitialCodeCacheSize and -XX:ReservedCodeCacheSizeSymbols
-XX:StringTableSizeDirectMemory
-XX:MaxDirectMemorySize## native memory
jcmd <pid> VM.native_memory
jcmd <pid> VM.native_memory baseline
jcmd <pid> VM.native_memory summary.diff
Native Memory Tracking (NMT)
-XX:NativeMemoryTracking=off|sumary|detail
参考文档
Find my application memory foot print programmatically
Huge Memory allocated outside of Java Heap
Introduction to JVM Code Cache
Is there a way to measure direct memory usage in Java?
Native Memory Tracking in JVM
Default HotSpot Maximum Direct Memory Size
Memory Types in JVM
Diagnosing a Running JVM
Can a Java Application Use More Memory Than the Heap Size?