JVM监控及诊断工具-命令之jmap

Posted 爱上口袋的天空

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JVM监控及诊断工具-命令之jmap相关的知识,希望对你有一定的参考价值。

1、简介

jmap:导出内存映像文件&内存使用情况

jmap( JVM Memory Map):作用一方面是获取dump文件(堆转储快照文件,二进制文件),它还可以获取目标Java进程的内存相关信息,包括Java堆各区域的使用情况、堆中对象的统
计信息、类加载信息等开发人员可以在控制台中输入命令“jmap -help”查阅jmap工具的具体使用方式和一些标准选项配置

一般来说,使用jmap指令生成dump文件的操作算得上是最常用 的jmap命令之一,将堆中所有 存活对象导出至一个文件之中。 Heap Dump又叫做堆存储文件,指一个Java进程在某个时间点 的内存快照。 Heap Dump在触 发内存快照的时候会保存此刻的信息如下

All Objects
        Class, fields, primitive values and references
All Classes
        Classloader, name, super class, static fields
Garbage Collection Roots
        Objects defined to be reachable by the JVM
Thread Stacks and Local Variables
        The call-stacks of threads at the moment of the snapshot, and per-frame
information about local objects
说明
1、通常在写 Heap Dump文件前会触发一次Full GC,所以 heap dump文件里保存的
   都是 Fu116C后留下的对象信息(这个针对的是自动的方式)
2、由于生成dump文件比较耗时,因此大家需要耐心等待,尤其是大内存镜像生成
   dump文件则需要耗费更长的时间来完成


2、导出内存映像文件

测试的程序代码如下:

package com.kgf.kgfjavalearning2021.jvm;

import java.util.ArrayList;

/***
 * 设置内存大小:-Xmx60m -XX:SurvivorRatio=8
 *
 */
public class JmapTest 

    public static void main(String[] args) 

        ArrayList<byte[]> list = new ArrayList<>();

        for (int i = 0; i < 1000; i++) 
            byte[] arr = new byte[1024*100];//每次向list中存放100kb的字节数组
            list.add(arr);
            try 
                Thread.sleep(100);
             catch (InterruptedException e) 
                e.printStackTrace();
            
        
    


在idea添加环境参数:

2.1、手动的方式

2.1.1、首先启动程序

2.1.2、在cmd的黑窗口,使用如下的jmap命令导出dump镜像文件

命令:

      jmap -dump:format=b,file=d:\\1.hprof 进程的pid

      或者

      jmap -dump:live,format=b,file=d:\\1.hprof 进程的pid  

执行如下:

C:\\Users\\86136>jps
10992
13712 RemoteMavenServer
14240 KotlinCompileDaemon
7216 JmapTest
9280 Jps
11992 Launcher

C:\\Users\\86136> jmap -dump:format=b,file=d:\\1.hprof 7216
Dumping heap to D:\\1.hprof ...
Heap dump file created

C:\\Users\\86136> jmap -dump:format=b,file=d:\\2.hprof 7216
Dumping heap to D:\\2.hprof ...
Heap dump file created

C:\\Users\\86136> jmap -dump:live,format=b,file=d:\\3.hprof 7216
Dumping heap to D:\\3.hprof ...
Heap dump file created

C:\\Users\\86136>

dump-options主要有:

  • live 只dump存活的对象,如果不加则会dump所有对象
  • format=b 表示以二进制格式
  • file=filepath 输出到某个文件中

把java堆中的对象dump到本地文件,然后使用第三方工具进行分析,如MAT,JProfile,IBM的分析工具等

 2.2、自动的方式

当程序发生OOM退出系统时,一些瞬时信息都随着程序的终止而消失,而重现OOM问题往往比较困难或者耗时。此时若能在OOM时,自动导出dump文件就显得非常迫切。
这里介绍一种比较常用的取得堆快照文件的方法,即使用
-XX:+HeapDumpOnOutOfMemoryError:在程序发生OOM时,导出应用程序的当前堆快照。-XX: HeapDumpPath:可以指定堆快照的保存位置。比如
-Xmx100m -XX: +HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=D: \\m.hprof

我们在我们测试的测试配置上添加上面的配置:

 

启动程序等待一会儿:

 


3、显示堆内存相关的信息

 

3.1、jmap -heap pid

 

Attaching to process ID 10452, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 25.51-b03

using thread-local object allocation.
Parallel GC with 10 thread(s)

Heap Configuration:
   MinHeapFreeRatio         = 0
   MaxHeapFreeRatio         = 100
   MaxHeapSize              = 62914560 (60.0MB)
   NewSize                  = 20971520 (20.0MB)
   MaxNewSize               = 20971520 (20.0MB)
   OldSize                  = 41943040 (40.0MB)
   NewRatio                 = 2
   SurvivorRatio            = 8
   MetaspaceSize            = 21807104 (20.796875MB)
   CompressedClassSpaceSize = 1073741824 (1024.0MB)
   MaxMetaspaceSize         = 17592186044415 MB
   G1HeapRegionSize         = 0 (0.0MB)

Heap Usage:
PS Young Generation
Eden Space:
   capacity = 16777216 (16.0MB)
   used     = 13348112 (12.729751586914062MB)
   free     = 3429104 (3.2702484130859375MB)
   79.56094741821289% used
From Space:
   capacity = 2097152 (2.0MB)
   used     = 2064640 (1.968994140625MB)
   free     = 32512 (0.031005859375MB)
   98.44970703125% used
To Space:
   capacity = 2097152 (2.0MB)
   used     = 0 (0.0MB)
   free     = 2097152 (2.0MB)
   0.0% used
PS Old Generation
   capacity = 41943040 (40.0MB)
   used     = 11481160 (10.949287414550781MB)
   free     = 30461880 (29.05071258544922MB)
   27.373218536376953% used

3043 interned Strings occupying 251216 bytes.

 可以看出上面详细的打印出了堆空间的内存信息情况!

 3.2、jmap -histo pid


 num     #instances         #bytes  class name
----------------------------------------------
   1:           860       40593688  [B
   2:          4967         516376  [C
   3:           185         195832  [I
   4:          4806         115344  java.lang.String
   5:           691          78872  java.lang.Class
   6:           679          48832  [Ljava.lang.Object;
   7:           785          31400  java.util.TreeMap$Entry
   8:           722          28880  java.util.LinkedHashMap$Entry
   9:           400          18368  [Ljava.lang.String;
  10:           539          17248  java.util.HashMap$Node
  11:           183          11712  java.net.URL
  12:            24          10368  [Ljava.util.HashMap$Node;
  13:           317           7608  java.util.LinkedList$Node
  14:           103           7416  java.lang.reflect.Field
  15:            67           5360  [Ljava.util.WeakHashMap$Entry;
  16:            54           5184  java.util.jar.JarFile$JarFileEntry
  17:           160           5120  java.util.LinkedList
  18:           123           4920  java.lang.ref.Finalizer
  19:            90           4320  sun.misc.URLClassPath$JarLoader
  20:           107           4280  java.lang.ref.SoftReference
  21:           256           4096  java.lang.Integer
  22:            64           4096  java.util.jar.JarFile
  23:           119           3808  java.util.Hashtable$Entry
  24:            66           3696  sun.nio.cs.UTF_8$Encoder
  25:           110           3520  java.util.concurrent.ConcurrentHashMap$Node
  26:           136           3264  java.io.ExpiringCache$Entry
  27:            67           3216  java.util.WeakHashMap
  28:             8           3008  java.lang.Thread
  29:            50           2400  java.util.zip.Inflater
  30:            73           2336  java.lang.ref.ReferenceQueue
  31:            26           2080  java.lang.reflect.Constructor
  32:            64           2048  java.util.zip.ZipCoder
  33:            14           1888  [Ljava.util.concurrent.ConcurrentHashMap$Node;
  34:            39           1872  sun.util.locale.LocaleObjectCache$CacheEntry
  35:            64           1536  java.util.ArrayDeque
  36:            32           1536  java.util.HashMap
  37:             1           1520  [[B
  38:            88           1408  java.lang.Object
  39:            24           1344  java.lang.Class$ReflectionData
  40:            19           1216  java.util.concurrent.ConcurrentHashMap
  41:            30           1200  java.io.ObjectStreamField
  42:            75           1200  java.lang.ref.ReferenceQueue$Lock
  43:            50           1200  java.util.zip.ZStreamRef
  44:             9           1184  [Ljava.util.Hashtable$Entry;
  45:             2           1064  [Ljava.lang.invoke.MethodHandle;
  46:             1           1040  [Ljava.lang.Integer;
  47:             1           1040  [[C
  48:            19            760  sun.util.locale.BaseLocale$Key
  49:            19            608  java.io.File
  50:            19            608  java.util.Locale
  51:            19            608  sun.util.locale.BaseLocale
  52:             9            576  [Ljava.lang.reflect.Field;
  53:            13            520  java.security.AccessControlContext
  54:            21            504  java.util.jar.Attributes$Name
  55:            19            456  java.util.Locale$LocaleKey
  56:            18            432  sun.misc.MetaIndex
  57:             1            384  com.intellij.rt.execution.application.AppMainV2$1
  58:             1            384  java.lang.ref.Finalizer$FinalizerThread
  59:             6            384  java.nio.DirectByteBuffer
  60:             1            376  java.lang.ref.Reference$ReferenceHandler
  61:            12            344  [Ljava.io.ObjectStreamField;
  62:             6            336  java.nio.DirectLongBufferU
  63:            17            328  [Ljava.lang.Class;
  64:             4            320  [S
  65:            10            320  java.lang.OutOfMemoryError
  66:             3            312  [D
  67:            13            312  [Ljava.lang.reflect.Constructor;
  68:            13            312  sun.reflect.NativeConstructorAccessorImpl
  69:            12            288  java.util.ArrayList
  70:             5            280  sun.util.calendar.ZoneInfo
  71:             3            264  java.lang.reflect.Method
  72:             8            256  java.util.Vector
  73:             3            240  [Ljava.lang.ThreadLocal$ThreadLocalMap$Entry;
  74:             5            240  java.util.Hashtable
  75:             4            224  java.util.LinkedHashMap
  76:             2            216  [J
  77:            13            208  sun.reflect.DelegatingConstructorAccessorImpl
  78:             5            200  java.security.ProtectionDomain
  79:             5            200  java.util.WeakHashMap$Entry
  80:             6            192  java.nio.file.attribute.FileTime
  81:             4            192  java.util.Properties
  82:             4            192  java.util.TreeMap
  83:             3            192  sun.nio.cs.ext.DoubleByte$Encoder
  84:             3            168  java.util.ResourceBundle$CacheKey
  85:             2            160  [[Ljava.lang.String;
  86:             4            160  java.io.FileDescriptor
  87:             4            160  java.lang.ClassLoader$NativeLibrary
  88:             5            160  java.lang.ThreadLocal$ThreadLocalMap$Entry
  89:             5            160  java.security.CodeSource
  90:             5            160  sun.util.locale.provider.LocaleProviderAdapter$Type
  91:             3            144  java.nio.HeapByteBuffer
  92:             3            144  java.util.ResourceBundle$BundleReference
  93:             6            144  sun.misc.PerfCounter
  94:             3            144  sun.misc.URLClassPath
  95:             2            128  java.io.ExpiringCache$1
  96:             4            128  java.util.Stack
  97:             1            120  java.net.SocksSocketImpl
  98:             5            120  java.util.Collections$UnmodifiableRandomAccessList
  99:             5            120  sun.misc.FloatingDecimal$PreparedASCIIToBinaryBuffer
 100:             2            112  java.lang.Package
 101:             2            112  sun.nio.cs.ext.DoubleByte$Decoder
 102:             4             96  java.lang.RuntimePermission
 103:             3             96  java.lang.StringCoding$StringEncoder
 104:             2             96  java.lang.ThreadGroup
 105:             3             96  java.lang.ref.WeakReference
 106:             3             96  java.util.ResourceBundle$LoaderReference
 107:             1             96  sun.misc.Launcher$AppClassLoader
 108:             3             96  sun.net.spi.DefaultProxySelector$NonProxyInfo
 109:             2             96  sun.nio.cs.StreamEncoder
 110:             1             88  java.net.DualStackPlainSocketImpl
 111:             1             88  sun.misc.Launcher$ExtClassLoader
 112:             5             80  [Ljava.security.Principal;
 113:             2             80  java.io.BufferedWriter
 114:             2             80  java.io.ExpiringCache
 115:             5             80  java.security.ProtectionDomain$Key
 116:             2             80  sun.misc.FloatingDecimal$BinaryToASCIIBuffer
 117:             3             72  java.lang.ThreadLocal$ThreadLocalMap
 118:             3             72  java.net.Proxy$Type
 119:             3             72  java.util.Arrays$ArrayList
 120:             3             72  java.util.Collections$SynchronizedSet
 121:             1             72  java.util.ResourceBundle$RBClassLoader
 122:             3             72  sun.misc.FloatingDecimal$ExceptionalBinaryToASCIIBuffer
 123:             1             72  sun.util.locale.provider.JRELocaleProviderAdapter
 124:             1             64  [F
 125:             2             64  [Ljava.lang.Thread;
 126:             2             64  java.io.FileOutputStream
 127:             2             64  java.io.FilePermission
 128:             2             64  java.io.PrintStream
 129:             2             64  java.lang.ClassValue$Entry
 130:             2             64  java.lang.StringCoding$StringDecoder
 131:             2             64  java.lang.VirtualMachineError
 132:             2             64  java.lang.ref.ReferenceQueue$Null
 133:             2             64  java.security.BasicPermissionCollection
 134:             2             64  java.security.Permissions
 135:             4             64  java.util.HashSet
 136:             2             48  [Ljava.lang.reflect.Method;
 137:             1             48  [Ljava.util.concurrent.TimeUnit;
 138:             2             48  java.io.BufferedOutputStream
 139:             1             48  java.io.BufferedReader
 140:             2             48  java.io.File$PathStatus
 141:             2             48  java.io.FilePermissionCollection
 142:             2             48  java.io.OutputStreamWriter
 143:             3             48  java.lang.ThreadLocal
 144:             2             48  java.net.InetAddress$Cache
 145:             2             48  java.net.InetAddress$Cache$Type
 146:             1             48  java.net.SocketInputStream
 147:             1             48  java.nio.HeapCharBuffer
 148:             2             48  java.nio.charset.CoderResult
 149:             3             48  java.nio.charset.CodingErrorAction
 150:             2             48  sun.misc.JarIndex
 151:             2             48  sun.misc.NativeSignalHandler
 152:             2             48  sun.misc.Signal
 153:             3             48  sun.net.www.protocol.jar.Handler
 154:             1             48  sun.nio.cs.StreamDecoder
 155:             1             48  sun.nio.cs.US_ASCII$Decoder
 156:             1             48  sun.util.locale.provider.LocaleResources$ResourceReference
 157:             1             48  sun.util.resources.TimeZoneNames
 158:             1             48  sun.util.resources.en.TimeZoneNames_en
 159:             1             40  [Lsun.util.locale.provider.LocaleProviderAdapter$Type;
 160:             1             40  java.io.BufferedInputStream
 161:             1             40  java.util.ResourceBundle$1
 162:             1             40  sun.nio.cs.StandardCharsets$Aliases
 163:             1             40  sun.nio.cs.StandardCharsets$Cache
 164:             1             40  sun.nio.cs.StandardCharsets$Classes
 165:             1             40  sun.nio.cs.ext.ExtendedCharsets
 166:             1             32  [Ljava.lang.OutOfMemoryError;
 167:             2             32  [Ljava.lang.StackTraceElement;
 168:             1             32  [Ljava.lang.ThreadGroup;
 169:             1             32  [Ljava.net.Proxy$Type;
 170:             1             32  java.io.FileInputStream
 171:             1             32  java.io.WinNTFileSystem
 172:             1             32  java.lang.ArithmeticException
 173:             2             32  java.lang.Boolean
 174:             1             32  java.lang.NullPointerException
 175:             1             32  java.net.InetAddress$InetAddressHolder
 176:             1             32  java.net.Socket
 177:             2             32  java.nio.ByteOrder
 178:             2             32  java.util.LinkedHashMap$LinkedKeySet
 179:             2             32  java.util.concurrent.atomic.AtomicInteger
 180:             1             32  java.util.concurrent.atomic.AtomicReferenceFieldUpdater$AtomicReferenceFieldUpdaterImpl
 181:             1             32  sun.instrument.InstrumentationImpl
 182:             1             32  sun.nio.cs.StandardCharsets
 183:             1             32  sun.util.locale.provider.LocaleResources
 184:             1             32  sun.util.locale.provider.LocaleServiceProviderPool
 185:             1             24  [Ljava.io.File$PathStatus;
 186:             1             24  [Ljava.lang.ClassValue$Entry;
 187:             1             24  [Ljava.net.InetAddress$Cache$Type;
 188:             1             24  [Ljava.security.ProtectionDomain;
 189:             1             24  [Lsun.launcher.LauncherHelper;
 190:             1             24  java.io.InputStreamReader
 191:             1             24  java.lang.ClassValue$Version
 192:             1             24  java.lang.StringBuilder
 193:             1             24  java.lang.invoke.MethodHandleImpl$4
 194:             1             24  java.lang.reflect.ReflectPermission
 195:             1             24  java.net.Inet4Address
 196:             1             24  java.net.Inet6AddressImpl
 197:             1             24  java.net.Proxy
 198:             1             24  java.util.BitSet
 199:             1             24  java.util.Collections$EmptyMap
 200:             1             24  java.util.Collections$SetFromMap
 201:             1             24  java.util.Locale$Cache
 202:             1             24  java.util.ResourceBundle$Control$CandidateListCache
 203:             1             24  java.util.concurrent.TimeUnit$1
 204:             1             24  java.util.concurrent.TimeUnit$2
 205:             1             24  java.util.concurrent.TimeUnit$3
 206:             1             24  java.util.concurrent.TimeUnit$4
 207:             1             24  java.util.concurrent.TimeUnit$5
 208:             1             24  java.util.concurrent.TimeUnit$6
 209:             1             24  java.util.concurrent.TimeUnit$7
 210:             1             24  java.util.jar.Manifest
 211:             1             24  sun.instrument.TransformerManager
 212:             1             24  sun.launcher.LauncherHelper
 213:             1             24  sun.misc.URLClassPath$FileLoader
 214:             1             24  sun.nio.cs.ISO_8859_1
 215:             1             24  sun.nio.cs.US_ASCII
 216:             1             24  sun.nio.cs.UTF_16
 217:             1             24  sun.nio.cs.UTF_16BE
 218:             1             24  sun.nio.cs.UTF_16LE
 219:             1             24  sun.nio.cs.UTF_8
 220:             1             24  sun.nio.cs.ext.GBK
 221:             1             24  sun.reflect.NativeMethodAccessorImpl
 222:             1             24  sun.util.locale.BaseLocale$Cache
 223:             1             24  sun.util.locale.provider.TimeZoneNameProviderImpl
 224:             1             16  [Ljava.lang.Throwable;
 225:             1             16  [Ljava.security.cert.Certificate;
 226:             1             16  [Lsun.instrument.TransformerManager$TransformerInfo;
 227:             1             16  java.io.FileDescriptor$1
 228:             1             16  java.lang.CharacterDataLatin1
 229:             1             16  java.lang.ClassValue$Identity
 230:             1             16  java.lang.Runtime
 231:             1             16  java.lang.String$CaseInsensitiveComparator
 232:             1             16  java.lang.System$2
 233:             1             16  java.lang.Terminator$1
 234:             1             16  java.lang.invoke.MemberName$Factory
 235:             1             16  java.lang.invoke.MethodHandleImpl$2
 236:             1             16  java.lang.invoke.MethodHandleImpl$3
 237:             1             16  java.lang.ref.Reference$Lock
 238:             1             16  java.lang.reflect.ReflectAccess
 239:             1             16  java.net.InetAddress$2
 240:             1             16  java.net.URLClassLoader$7
 241:             1             16  java.nio.Bits$1
 242:             1             16  java.nio.charset.CoderResult$1
 243:             1             16  java.nio.charset.CoderResult$2
 244:             1             16  java.security.ProtectionDomain$1
 245:             1             16  java.security.ProtectionDomain$3
 246:             1             16  java.util.Collections$EmptyList
 247:             1             16  java.util.Collections$EmptySet
 248:             1             16  java.util.Hashtable$EntrySet
 249:             1             16  java.util.ResourceBundle$Control
 250:             1             16  java.util.WeakHashMap$KeySet
 251:             1             16  java.util.jar.Attributes
 252:             1             16  java.util.jar.JavaUtilJarAccessImpl
 253:             1             16  java.util.zip.ZipFile$1
 254:             1             16  sun.misc.ASCIICaseInsensitiveComparator
 255:             1             16  sun.misc.FloatingDecimal$1
 256:             1             16  sun.misc.Launcher
 257:             1             16  sun.misc.Launcher$Factory
 258:             1             16  sun.misc.Perf
 259:             1             16  sun.misc.Unsafe
 260:             1             16  sun.net.spi.DefaultProxySelector
 261:             1             16  sun.net.www.protocol.file.Handler
 262:             1             16  sun.reflect.DelegatingMethodAccessorImpl
 263:             1             16  sun.reflect.ReflectionFactory
 264:             1             16  sun.util.calendar.Gregorian
 265:             1             16  sun.util.locale.provider.AuxLocaleProviderAdapter$NullProvider
 266:             1             16  sun.util.locale.provider.SPILocaleProviderAdapter
 267:             1             16  sun.util.locale.provider.TimeZoneNameUtility$TimeZoneNameGetter
 268:             1             16  sun.util.resources.LocaleData
 269:             1             16  sun.util.resources.LocaleData$LocaleDataResourceBundleControl
Total         17976       41790336

上面打印出来了在程序运行过程中出现的大对象情况! 


 4、总结

        由于jmap将访问堆中的所有对象,为了保证在此过程中不被应用线程干扰,jmap需要借助安全点机制,让所有线程停留在不改变堆中数据的状态。也就是说,由jmap导出的堆快照必定是安全点位置的。这可能导致基于该堆快照的分析结果存在偏差。
        举个例子,假设在编译生成的机器码中,某些对象的生命周期在两个安全点之间,那么
live选项将无法探知到这些对象。另外,如果某个线程长时间无法跑到安全点,jmap将一直等下去。与前面讲的 jstat则不同,垃圾回收器会主动将 jstat所需要的摘要数据保存至固定位置之中,而jstat只需直接读取即可。

以上是关于JVM监控及诊断工具-命令之jmap的主要内容,如果未能解决你的问题,请参考以下文章

JVM监控及诊断工具-命令之jhat

JVM监控诊断之命令行使用

JVM监控诊断之命令行使用

JVM监控诊断之命令行使用

JVM监控及诊断工具-命令之jstat

JVM监控及诊断工具-命令之jstack