JVM Part 2: Performance Monitoring and Tuning_02_JVM Monitoring and Diagnostic Tools - Command Line_Silicon Valley

1 Overview

overview

​ Performance diagnosis is a problem that software engineers often face and solve in their daily work. Today, when user experience is paramount, solving application performance problems can bring great benefits.

Java is one of the most popular programming languages, and its application performance diagnosis has been widely concerned by the industry. There are many factors that may cause performance problems in Java applications, such as thread control, disk read and write, database access, network I/O, garbage collection, and so on. To locate these problems, an excellent performance diagnostic tool is essential.

Experience 1: Use data description, use knowledge to analyze problems, and use tools to deal with problems.

Experience 2: No monitoring, no tuning!

Simple command line tool

Under the bin directory of jdk, there are some auxiliary tools

image-20220918212555689

View the specific source address: https://hg.openjdk.java.net/jdk/jdk11/file/1ddf9a99e4ad/src/jdk.jcmd/share/classes/sun/tools

2-jps: View the running Java process

basic situation

jps (Java Process Status) (Common)

Display all HotSpot virtual machine processes in the specified system (view virtual machine process information), which can be used to query the running virtual machine processes.

Note: For a local virtual machine process, the local virtual machine ID of the process is consistent with the process ID of the operating system and is unique.

Basic syntax:

Its basic usage syntax is:

jps [options] [hostid]

You can jps -helpview the corresponding parameter information by

options parameter

We can also print additional information by appending parameters.

-q: Only display LVMID (local virtual machine id), which is the unique id of the local virtual machine. Do not display the name of the main class, etc.

-l: output the full class name of the main class of the application or if the process executes the jar package, output the full path of the jar

-m: Output the parameters passed to the main class main() when the virtual machine process starts

-v: List the JVM parameters when the virtual machine process starts. For example: -Xms20m -Xmx50m is the jvm parameter specified by the startup program.

Note: The above parameters can be used in combination.

Replenish:

If a Java process turns off the default start UsePerfData parameter (that is, use the parameter -XX: -UsePerfData), then the jps command (and the jstat described below) will not be able to detect the Java process.

Example:

C:\Users\86156>jps
23652 RemoteMavenServer36
8580
17804 Jps

C:\Users\86156>jps -q
23652
8580
6540

C:\Users\86156>jps -l
9568 sun.tools.jps.Jps
23652 org.jetbrains.idea.maven.server.RemoteMavenServer36
8580

C:\Users\86156>jps -m
23652 RemoteMavenServer36
8580
17112 Jps -m

C:\Users\86156>jps -v
23652 RemoteMavenServer36 -Djava.awt.headless=true -Dmaven.defaultProjectBuilder.disableGlobalModelCache=true -Didea.version=2022.1.2 -Didea.maven.embedder.version=3.6.1 -Xmx768m -Dmaven.ext.class.path=D:\Program Files\JetBrains\IntelliJ IDEA 2022.1.2\plugins\maven\lib\maven-event-listener.jar -Dfile.encoding=GBK
8580  exit -Xms128m -Xmx750m -XX:ReservedCodeCacheSize=512m -XX:+IgnoreUnrecognizedVMOptions -XX:+UseG1GC -XX:SoftRefLRUPolicyMSPerMB=50 -XX:CICompilerCount=2 -XX:+HeapDumpOnOutOfMemoryError -XX:-OmitStackTraceInFastThrow -ea -Dsun.io.useCanonCaches=false -Djdk.http.auth.tunneling.disabledSchemes="" -Djdk.attach.allowAttachSelf=true -Djdk.module.illegalAccess.silent=true -Dkotlinx.coroutines.debug=off -Xmx2029m -javaagent:D:\coding\plugins\jet-code\jet-code.jar -Djb.vmOptionsFile=C:\Users\86156\AppData\Roaming\JetBrains\IntelliJIdea2022.1\idea64.exe.vmoptions -Djava.system.class.loader=com.intellij.util.lang.PathClassLoader -Didea.strict.classpath=true -Didea.vendor.name=JetBrains -Didea.paths.selector=IntelliJIdea2022.1 -Didea.jre.check=true -Dsplash=true -Dide.native.launcher=true -XX:ErrorFile=C:\Users\86156\java_error_in_idea64_%p.log -XX:HeapDumpPath=C:\Users\86156\java_error_in_idea64.hprof
8792 Jps -Dapplication.home=D:\coding\java\jdk\jdk1.8.0_341 -Xms8m

hostid parameter

The hostname registered in the RMI registry.

​ If you want to remotely monitor the java program on the host, you need to install jstatd

For sites with stricter security practices, a custom policy file may be used to show access to specific trusted hosts or networks, although this technique is vulnerable to IP address spoofing attacks .

​ If the security issue cannot be handled using a fixed value policy file, then the safest operation is not to run the jstatd server, but to use the jstat and jps tools locally.

3-jstat: view JVM statistics

Basic Information

​ jstat (JVM Statistics Monitoring Tool): A command-line tool for monitoring various running status information of virtual machines. It can display running data such as class loading, memory, garbage collection, JIT compilation, etc. in local or remote virtual machine processes.

​ On a server that does not have a GUI graphical interface and only provides a plain text console environment, it will be the preferred tool for locating virtual machine performance problems during runtime. Commonly used to monitor garbage collection issues and memory leaks.

Official documentation: https://docs.oracle.com/javase/8/docs/technotes/tools/unix/jstat.html

basic grammar

jstat - [-t] [-h] [ []]

View command related parameters:

jstat -h or jstat -help

option parameter

The option option can consist of the following values.

  • class loading related
    • -class: Display the relevant information of ClassLoader: class loading, unloading quantity, total space, time consumed by class loading, etc.
C:\Users\86156>jstat -class 23104
Loaded  Bytes  Unloaded  Bytes     Time
 13995 14406.4       41    30.6       9.48
  • garbage collection related
    • -gc: Display heap information related to GC. Including the Eden area, the two Survivor areas, the capacity of the old generation, the permanent generation, etc., the used space, the total GC time and other information.
    • -gccapacity: The display content is basically the same as -gc, but the output focuses on the maximum and minimum space used by each area of ​​the Java heap. Shows the proportion
    • -gcutil: The display content is basically the same as -gc, but the output mainly focuses on the percentage of the used space to the total space.
    • gccause: Same as -gcutil, but will additionally output the cause of the last or current GC.
    • -gcnew: Display the GC status of the new generation
    • -gcnewcapacity: The display content is basically the same as -gcnew, and the output mainly focuses on the maximum and minimum space used
    • -geold: display the GC status of the old age

-gc print example:

C:\Users\86156>jstat -gc 23104
 S0C    S1C    S0U    S1U      EC       EU        OC         OU       MC     MU    CCSC   CCSU   YGC     YGCT    FGC    FGCT     GCT
5504.0 5504.0 1217.9  0.0   44032.0  16226.1   110024.0   101890.8  53888.0 51191.8  0.0    0.0      308    1.437   6      0.415    1.852

-gc print attribute explanation

New generation related

  • S0C is the size of the first survivor area (bytes)
  • S1C is the size of the second survivor area (bytes)
  • S0U is the used size (bytes) of the first survivor area
  • S1U is the used size (bytes) of the second survivor
  • EC is the size of the Eden space (bytes)
  • EU is the used size of Eden space (bytes)

Old age related

  • OC is the size of the old generation (bytes)
  • OU is the used size (bytes) of the old generation

Method area (metaspace) related

  • MC is the size of the method area
  • MU is the used size of the method area
  • CCSC is the size of the compressed class space
  • CCSU is the used size of the compressed class space

other

  • YGC refers to the number of young gc when the application starts to sample
  • YGCT refers to the young gc consumption time (seconds) from application startup to sampling
  • FGC is the number of times from application startup to sampling full gc
  • FGCT is the consumption time (seconds) of full gc from application startup to sampling
  • GCT is the total time of gc from application start to sample time
C:\Users\86156>jstat -gcutil 17840 1000 10
  S0     S1     E      O      M     CCS    YGC     YGCT    FGC    FGCT     GCT
  0.00   8.15  59.98  67.65  98.50      -    305    1.216     6    0.325    1.541
  0.00   8.15  60.32  67.65  98.50      -    305    1.216     6    0.325    1.541
  0.00   8.15  60.60  67.65  98.50      -    305    1.216     6    0.325    1.541
  
  C:\Users\86156>jstat -gcutil 17840 1000 10
  S0     S1     E      O      M     CCS    YGC     YGCT    FGC    FGCT     GCT
  0.00   8.15  59.98  67.65  98.50      -    305    1.216     6    0.325    1.541
  0.00   8.15  60.32  67.65  98.50      -    305    1.216     6    0.325    1.541
  0.00   8.15  60.60  67.65  98.50      -    305    1.216     6    0.325    1.541
  
  C:\Users\86156>jstat -gccapacity -t 17840 1000 10
Timestamp        NGCMN    NGCMX     NGC     S0C   S1C       EC      OGCMN      OGCMX       OGC         OC       MCMN     MCMX      MC     CCSMN    CCSMX     CCSC    YGC    FGC
        21443.7   5440.0  87360.0  47680.0 4736.0 4736.0  38208.0    10944.0   174784.0    95308.0    95308.0      0.0  43392.0  43392.0      0.0      0.0      0.0    308     6
        21444.7   5440.0  87360.0  47680.0 4736.0 4736.0  38208.0    10944.0   174784.0    95308.0    95308.0      0.0  43392.0  43392.0      0.0      0.0      0.0    308     6
        21445.7   5440.0  87360.0  47680.0 4736.0 4736.0  38208.0    10944.0   174784.0    95308.0    95308.0      0.0  43392.0  43392.0      0.0      0.0      0.0    308     6
        21446.7   5440.0  87360.0  47680.0 4736.0 4736.0  38208.0    10944.0   174784.0    95308.0    95308.0      0.0  43392.0  43392.0      0.0      0.0      0.0    308     6
        21447.8   5440.0  87360.0  47680.0 4736.0 4736.0  38208.0    10944.0   174784.0    95308.0    95308.0      0.0  43392.0  43392.0      0.0      0.0      0.0    308     6
  • JIT-related:
    • -compiler: Display information such as the method compiled by the JIT compiler, time-consuming, etc.
    • -printcompilation: Output methods that have been JIT compiled
C:\Users\86156>jstat -compiler 23104
Compiled Failed Invalid   Time   FailedType FailedMethod
    8686      7       0     2.22          1 com/alibaba/fastjson/parser/deserializer/JavaBeanDeserializer deserialze

C:\Users\86156>jstat -printcompilation 23104
Compiled  Size  Type Method
    8687     21    1 java/nio/channels/spi/AbstractSelector isOpen

interval parameter

It is used to specify the cycle of data statistics, in milliseconds. That is: view interval

  每隔一秒钟打印一次
C:\Users\86156>jstat -class 23104 1000
Loaded  Bytes  Unloaded  Bytes     Time
 13975 14387.3       41    30.6       9.47
 13975 14387.3       41    30.6       9.47
 13975 14387.3       41    30.6       9.47

count parameter

The total number of times used to specify the query

 每隔一秒钟打印一次 打印3次
C:\Users\86156>jstat -class 23104 1000 3
Loaded  Bytes  Unloaded  Bytes     Time
 13976 14387.8       41    30.6       9.47
 13976 14387.8       41    30.6       9.47
 13976 14387.8       41    30.6       9.47

-t parameter

You can add a TimeStamp column before the output information to show the running time of the program. unit

C:\Users\86156>jstat -class -t 23104
Timestamp       Loaded  Bytes  Unloaded  Bytes     Time
          777.3  13977 14388.3       41    30.6       9.47

experience:

We can compare the startup time of the Java process and the total GC time (GCT column), or the delta of the two measured times and the total GC time, to get the ratio of GC time.

If the ratio exceeds 20%, it means that the GC pressure of the heap is currently high; if the ratio exceeds 90%, it means that there is almost no free space in the heap, and an OOM exception may be thrown at any time.

-h parameter

It is possible to output a table header information after outputting how many rows of data during periodic data output

C:\Users\86156>jstat -class -h3 23104 1000
Loaded  Bytes  Unloaded  Bytes     Time
 13977 14388.3       41    30.6       9.47
 13977 14388.3       41    30.6       9.47
 13977 14388.3       41    30.6       9.47
Loaded  Bytes  Unloaded  Bytes     Time
 13977 14388.3       41    30.6       9.47
 13977 14388.3       41    30.6       9.47
 13977 14388.3       41    30.6       9.47
Loaded  Bytes  Unloaded  Bytes     Time
 13977 14388.3       41    30.6       9.47
 13977 14388.3       41    30.6       9.47
 13977 14388.3       41    30.6       9.47

Replenish

jstat can also be used to determine whether there is a memory leak

step 1

In a long-running Java program, we can run the jstat command to continuously obtain multiple rows of performance data, and take the minimum value of the OU column (that is, the occupied old memory) in these rows of data.

step 2

​ Then, we repeat the above operation every longer period of time to obtain multiple groups of OU minimum values. If these values ​​show an upward trend, it means that the usage of the old age of the Java program is constantly increasing, which means that objects that cannot be recycled are constantly increasing and decreasing, so there is a high possibility of memory leaks.

4-jinfo: View and modify JVM configuration parameters in real time

basic situation

jinfo(Configuration Info for Java)

View virtual machine configuration parameter information, and can also be used to adjust virtual machine configuration parameters.

In many cases, Java applications do not specify all Java virtual machine parameters. At this time, developers may not know the default value of a specific Java virtual machine parameter. In this case, it may be necessary to find someone's documentation for a certain parameter. This search process can be very difficult. But with the jinfo tool, developers can easily find the current value of the Java virtual machine parameters.

Official help documentation:

https://docs.oracle.com/en/java/javase/11/tools/jinfo.html

basic grammar

jinfo [ options ] pid

Description: The java process ID must be added

options Option Description
no option Export all parameters and system properties
-flag name Output the parameter corresponding to the name
-flag [±]name Turn on or off the parameter with the corresponding name. Only the parameter marked as manageable can be dynamically modified.
-flag name=value Set the parameter corresponding to the name
-flags output all parameters
-sysprops export system properties

Check

jinfo -sysprops PID can view the parameters obtained by System.getProperties()

C:\Users\86156>jinfo -sysprops 7788
Attaching to process ID 7788, please wait...
Debugger attached successfully.
Client compiler detected.
JVM version is 25.341-b10
jboss.modules.system.pkgs = com.intellij.rt
java.vendor = Oracle Corporation
sun.java.launcher = SUN_STANDARD
catalina.base = C:\Users\86156\AppData\Local\Temp\tongweb.2698240303654290733.7088
sun.management.compiler = HotSpot Client Compiler
catalina.useNaming = false
spring.output.ansi.enabled = always
os.name = Windows 11
sun.boot.class.path = D:\coding\java\jdk\jdk1.8.0_341\jre\lib\resources.jar;D:\coding\java\jdk\jdk1.8.0_341\jre\lib\rt.jar;D:\coding\java\jdk\jdk1.8.0_341\jre\lib\jsse.jar;D:\coding\java\jdk\jdk1.8.0_341\jre\lib\jce.jar;D:\coding\java\jdk\jdk1.8.0_341\jre\lib\charsets.jar;D:\coding\java\jdk\jdk1.8.0_341\jre\lib\jfr.jar;D:\coding\java\jdk\jdk1.8.0_341\jre\classes;C:\Users\86156\AppData\Local\JetBrains\IntelliJIdea2022.1\captureAgent\debugger-agent.jar
LOG_LEVEL_PATTERN = %5p [swap-service,%X{
    
    X-B3-TraceId:-},%X{
    
    X-B3-SpanId:-},%X{
    
    X-Span-Export:-}]
sun.desktop = windows
spring.application.admin.enabled = true
com.sun.management.jmxremote =
java.vm.specification.vendor = Oracle Corporation
java.runtime.version = 1.8.0_341-b10
spring.liveBeansView.mbeanDomain =
user.name = 86156
spring.jmx.enabled = true
user.language = zh
sun.boot.library.path = D:\coding\java\jdk\jdk1.8.0_341\jre\bin
nacos.logging.path = C:\Users\86156/logs/nacos
PID = 7788
java.version = 1.8.0_341
user.timezone = Asia/Shanghai
sun.arch.data.model = 32
java.endorsed.dirs = D:\coding\java\jdk\jdk1.8.0_341\jre\lib\endorsed
java.rmi.server.randomIDs = true
sun.cpu.isalist =
sun.jnu.encoding = GBK
file.encoding.pkg = sun.io
file.separator = \
java.specification.name = Java Platform API Specification
java.class.version = 52.0
user.country = CN
java.home = D:\coding\java\jdk\jdk1.8.0_341\jre
java.vm.info = mixed mode
os.version = 10.0
path.separator = ;
java.vm.version = 25.341-b10
org.jboss.logging.provider = slf4j
user.variant =
http.maxRedirects = 5
java.awt.printerjob = sun.awt.windows.WPrinterJob
sun.io.unicode.encoding = UnicodeLittle
awt.toolkit = sun.awt.windows.WToolkit
user.script =
user.home = C:\Users\86156
java.specification.vendor = Oracle Corporation

jinfo -flags

C:\Users\86156>jinfo -flags 7788
Attaching to process ID 7788, please wait...
Debugger attached successfully.
Client compiler detected.
JVM version is 25.341-b10
Non-default VM flags: -XX:-BytecodeVerificationLocal -XX:-BytecodeVerificationRemote -XX:InitialHeapSize=16777216 -XX:+ManagementServer -XX:MaxHeapSize=268435456 -XX:MaxNewSize=89456640 -XX:MinHeapDeltaBytes=131072 -XX:NewSize=5570560 -XX:OldSize=11206656 -XX:TieredStopAtLevel=1 -XX:+UseFastUnorderedTimeStamps -XX:-UseLargePagesIndividualAllocation
Command line:  -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:56002,suspend=y,server=n -XX:TieredStopAtLevel=1 -Xverify:none -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true -javaagent:C:\Users\86156\AppData\Local\JetBrains\IntelliJIdea2022.1\captureAgent\debugger-agent.jar -Dfile.encoding=UTF-8 

 查看是否使用ParalllelGC
C:\Users\86156>jinfo -flag UseParallelGC 7788
-XX:-UseParallelGC

 查看是否使用G1垃圾回收器
C:\Users\86156>jinfo -flag UseG1GC 7788
-XX:-UseG1GC

C:\Users\86156>jinfo -flag MaxHeapSize 7788
-XX:MaxHeapSize=268435456

Revise

​ jinfo can not only view the actual value of a certain Java virtual machine parameter at runtime, but even modify some parameters at runtime and make it take effect immediately.

​ However, not all parameters support dynamic modification. Only parameters marked as manageable can be modified in real time. In fact, this modification capability is extremely limited.

  • For boolean type jinfo -flag [+|-] specific parameter PID
  • For boolean type jinfo -flag specific parameter = specific parameter value PID

expand

Linux view parameters marked as manageable

 说明
java -XX:+PrintFlagsFinal 8752 | grep manageable
 具体实践
java -XX:+PrintFlagsFinal 8752 | grep manageable 
     intx CMSAbortablePrecleanWaitMillis            = 100               {
    
    manageable}
     intx CMSTriggerInterval                        = -1                {
    
    manageable}
     intx CMSWaitDuration                           = 2000              {
    
    manageable}
     bool HeapDumpAfterFullGC                       = false             {
    
    manageable}
     bool HeapDumpBeforeFullGC                      = false             {
    
    manageable}
     bool HeapDumpOnOutOfMemoryError                = false             {
    
    manageable}
    ccstr HeapDumpPath                              =                   {
    
    manageable}
    uintx MaxHeapFreeRatio                          = 100               {
    
    manageable}
    uintx MinHeapFreeRatio                          = 0                 {
    
    manageable}
     bool PrintClassHistogram                       = false             {
    
    manageable}
     bool PrintClassHistogramAfterFullGC            = false             {
    
    manageable}
     bool PrintClassHistogramBeforeFullGC           = false             {
    
    manageable}
     bool PrintConcurrentLocks                      = false             {
    
    manageable}
     bool PrintGC                                   = false             {
    
    manageable}
     bool PrintGCDateStamps                         = false             {
    
    manageable}
     bool PrintGCDetails                            = false             {
    
    manageable}
     bool PrintGCID                                 = false             {
    
    manageable}
     bool PrintGCTimeStamps                         = false             {
    
    manageable}
Error: Could not find or load main class 8752

View the initial values ​​of all JVM parameter startup

java -XX:+PrintFlagsInitial

View the final values ​​of all JVM parameters

java -XX:+PrintFlagsFinal

View the names and values ​​of XX parameters that have been set in detail by the user or JVM

java -XX:+PrintCommandLineFlags

Modify parameters while JVM is running

 查看修改前的参数
C:\Users\86156>jinfo -flag PrintGCDetails 4816
-XX:-PrintGCDetails
 修改参数
C:\Users\86156>jinfo -flag +PrintGCDetails 4816
 查看修改后的情况
C:\Users\86156>jinfo -flag PrintGCDetails 4816
-XX:+PrintGCDetails

5-jmap: Export memory image file & memory usage

basic situation

jmap (JVM Memory Map): On the one hand, its function is to obtain dump files (heap dump snapshot files, binary files), and it can also obtain memory-related information of the target Java process, including the usage of each area of ​​the Java heap and the objects in the heap Statistics, classloading information, etc.

Developers can enter the command "jmap -help" in the console to view the specific usage of the jmap tool and some standard option configurations.

Official help documentation: https://docs.oracle.com/en/java/javase/11/tools/jmap.html

basic grammar

Its basic usage syntax is:

  • jmap [option]
  • jmap [option] <executable
  • jmap [option] [server_id@]

where option

options effect
-dump generate dump file
-finalizerinof Use ClassLoader as the statistical caliber to output the memory status information of the permanent generation
-heap Output detailed information of the entire heap space, including GC usage, heap configuration information, and memory usage information, etc.
-histo Output statistics of objects in the heap space, including class, number of instances, and total copper beams
-permstat Use ClassLoader as the statistical caliber to output the memory status information of the permanent generation
-F When the virtual machine process does not have any response to the -dump option, it is forced to generate a dump file

Note: These parameters are somewhat different from the commands entered and displayed under Linux, including the impact of the jdk version.

-dump

  • Generate a Java heap dump snapshot: dump file
  • Special: -dump:live saves only live objects in the heap

-heap

  • Output detailed information of the entire heap space, including GC usage, heap configuration information, and memory usage information, etc.
C:\Users\86156>jmap -heap 41048
Attaching to process ID 41048, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 25.144-b01

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

Heap Configuration:
   MinHeapFreeRatio         = 0
   MaxHeapFreeRatio         = 100
   MaxHeapSize              = 1073741824 (1024.0MB)
   NewSize                  = 88604672 (84.5MB)
   MaxNewSize               = 357564416 (341.0MB) // 新生代
   OldSize                  = 177733632 (169.5MB) // 老年代
   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 = 202375168 (193.0MB) // 容量
   used     = 54225104 (51.71308898925781MB)
   free     = 148150064 (141.2869110107422MB)
   26.79434662655845% used
From Space:
   capacity = 524288 (0.5MB)
   used     = 0 (0.0MB)
   free     = 524288 (0.5MB)
   0.0% used
To Space:
   capacity = 69730304 (66.5MB)
   used     = 0 (0.0MB)
   free     = 69730304 (66.5MB)
   0.0% used
PS Old Generation  // 老年代
   capacity = 284688384 (271.5MB) 
   used     = 105067264 (100.199951171875MB)
   free     = 179621120 (171.300048828125MB)
   36.906059363489874% used

48332 interned Strings occupying 5159400 bytes.

result

Attaching to process ID 2008, please wait...
Debugger attached successfully.
Client compiler detected.
JVM version is 25.341-b10

using thread-local object allocation.
Mark Sweep Compact GC

Heap Configuration:
   MinHeapFreeRatio         = 40
   MaxHeapFreeRatio         = 70
   MaxHeapSize              = 1073741824 (1024.0MB)
   NewSize                  = 5570560 (5.3125MB)
   MaxNewSize               = 357892096 (341.3125MB)
   OldSize                  = 11206656 (10.6875MB)
   NewRatio                 = 2
   SurvivorRatio            = 8
   MetaspaceSize            = 12582912 (12.0MB)
   CompressedClassSpaceSize = 1073741824 (1024.0MB)
   MaxMetaspaceSize         = 4294901760 (4095.9375MB)
   G1HeapRegionSize         = 0 (0.0MB)

Heap Usage:
New Generation (Eden + 1 Survivor Space):
   capacity = 48627712 (46.375MB)
   used     = 1811256 (1.7273483276367188MB)
   free     = 46816456 (44.64765167236328MB)
   3.7247403291357815% used
Eden Space:
   capacity = 43253760 (41.25MB)
   used     = 1098680 (1.0477828979492188MB)
   free     = 42155080 (40.20221710205078MB)
   2.5400797526041665% used
From Space:
   capacity = 5373952 (5.125MB)
   used     = 712576 (0.6795654296875MB)
   free     = 4661376 (4.4454345703125MB)
   13.259813262195122% used
To Space:
   capacity = 5373952 (5.125MB)
   used     = 0 (0.0MB)
   free     = 5373952 (5.125MB)
   0.0% used
tenured generation:
   capacity = 107827200 (102.83203125MB)
   used     = 88838416 (84.72291564941406MB)
   free     = 18988784 (18.109115600585938MB)
   82.38961597815765% used

47521 interned Strings occupying 4573456 bytes.

-histo

  • Output statistics about objects in the heap, including class, number of instances, and aggregate capacity
  • Special: -histo:live only counts live objects in the heap

Description of some types in results

[B =byte[]

[C = char

[I = int

[Lx is an array of type x

-permstat

  • Use ClassLoader as the statistical caliber to output the memory status object of the permanent generation
  • Only available on linux/solaris platform

-finalizerinfo

  • Display the objects waiting for the Finalize method in the F-Queue
  • Only available on linux/solaris platform

-F

  • When the virtual machine process does not respond to -dump, this option can be used to force the generation of a dump file
  • Only available on linux/solaris platform

-h | help

Help commands used by the jmap tool

-J

Pass parameters to the jvm enabled by jmap

Use 1: Export memory image file

manual way

jmap -dump:format=b,file=<filename.hprof> [pid]
jmap -dump:live,format=b,file=<filename.hprof> [pid]

 例如
jmap -dump:live,format=b,file=D:\hprof\oom.hprof 22488

illustrate

Generally speaking, the operation of using the jmap command to generate a dump file is one of the most commonly used jmap commands, which exports all surviving objects in the heap to a file.

Heap Dump, also known as a heap storage file, refers to a memory snapshot of a Java process at a certain point in time. When Heap Dump triggers a memory snapshot, it will save the information at this moment as follows:

  • All Objects

Class,fields,primitive value 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

illustrate:

1. Usually a Full GC is triggered before writing the Heap Dump file, so the heap dump file stores the object information left after the Full GC.

2. Since generating a dump file is time-consuming, you need to wait patiently, especially for a large memory image to generate a dump file, which takes longer to complete.

automatic way

When the program exits the system due to OOM, some transient information disappears with the termination of the program, and it is often difficult or time-consuming to reproduce the OOM problem. At this time, if it is possible to automatically export the dump file during OOM, it is very urgent.

Here is a more commonly used method to obtain heap snapshot files, that is, use:

-XX:+HeapDumpOnOutOfMemoryError: When the program OOM occurs, export the current heap snapshot of the application.

-XX:HeapDumpPath=<filename.hprof>: You can specify the save location of the heap snapshot.

-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=<filename.hprof>

Use 2: Display heap memory related information

jmap -heap pid

-jmap -tissue

summary

​ Since jmap will access all objects in the heap, in order to ensure that it will not be interfered by the application thread during this process, jmap needs to use the security point mechanism to keep all threads in the state of not changing the data in the heap. In other words, the heap snapshot exported by jmap must be at a safe point. This can lead to skewed analysis results based on that heap snapshot.

​ For example, assuming that in the machine code generated by compilation, the life cycle of some objects is between two safe points, then the :live option will not be able to detect these objects.

​ In addition, if a thread cannot run to a safe point for a long time, jmap will wait forever. Unlike the jstat mentioned above, the garbage collector will actively save the summary data required by jstat to a fixed location, while jstat only needs to be read directly.

6-jhat: JDK comes with a heap analysis tool

The jhat command is overflowed in jdk9 and later. The official recommendation is to use jvisualvm instead of jvm, so this command only needs a simple understanding.

basic situation

jhat(JVM Heap Analysis Tool)

The jhat command provided by Sun JDK is used together with the jmap command to analyze the heap dump file (heap dump snapshot) generated by jmap. jhat has a built-in WeChat HTTP/HTML server. After generating the analysis result of the dump file, the user can view the analysis result in the browser (analyze the dump snapshot information of the virtual machine).

Using the jhat command, i starts an http service, the port is 7000, that is, http://localhost:7000, and it can be analyzed in the browser.

Note: The jhat command has been deleted in JDK9 and JDK10. It is officially recommended to use VisualVM instead

basic grammar

jhat [option] [dumpfile]

Example:

jhat myjmapfile.hprof

Query using OQL

image-20221003002932353

basic grammar

image-20221003003225315

7-jstack: print thread snapshots in the JVM

basic situation

​ jstack (JVM Stack Trace): used to generate a thread snapshot (virtual machine stack trace) at the current moment of the specified process of the virtual machine. A thread snapshot is a collection of method stacks being executed by each thread of a specified process in the current virtual machine.

​ The function of generating thread snapshots: it can be used for the reasons of thread pauses for a long time, such as thread deadlock, infinite loop, long waiting caused by requesting external resources, etc. These are common causes of long thread pauses. When the thread pauses, you can use jstack to display the stack status of each thread call.

Mainly to check the status of the thread and which line of code the thread executes

Official help documentation: https://docs.oracle.com/en/java/javase/11/tools/jstack.html

In thread dump, pay attention to the following states

  • Deadlock, Deadlock (focus)
  • Waiting for resources, Waiting on condition (focus)
  • Waiting to acquire a monitor, Waiting on monitor entry (focus)
  • Blocking, Blocked (focus)
  • Executing, Runnable
  • Suspended

basic grammar

option parameter:

-F

  • When the request for normal output is not responded to, force the output thread stack

-l (lowercase L)

  • Show additional information about locks in addition to the stack

-m

  • If you call a native method, you can display the C/C++ stack

-h

  • help operation

example:

jstack -l 2008

8-jcmd: multifunctional command line

basic situation

​ After JDK1.7, a command line tool jcmd was added.

​ It is a multifunctional tool that can be used to realize the functions of all the previous commands except jstat. For example: use it to export heap, memory usage, view Java process, export thread information, perform GC, JVM runtime, etc.

​ jcmd has most of the functions of jmap, and it is also recommended to use the jcmd command instead of the jmap command on Oracle's official website

​ Official help documentation: https://docs.oracle.com/en/java/javase/11/tools/jcmd.html

basic grammar

jcmd -l

  • List all JVM processes

jcmd process number help

  • For the specified process, list all supported commands

jcmd pid specific command

  • Display data for the specified command of the specified process

image-20221003135008780

Replace the previous operations with the above command:

  • Thread.print can replace jstack instruction
  • GC.class_histogram can replace the -histo operation in jmap
  • GC.heap_dump can replace the -dump operation in jmap
  • GC.run can view the execution of GC
  • VM.uptime can view the total execution time of the program, and can replace the -t operation in the jstat command
  • VM.system_properties can replace jinfo -sysprops process id
  • VM.flags can get the configuration parameter information of JVM
  • GC.run manually triggers Full GC

9-jstatd: remote host information collection

​ The previous instructions only involved monitoring native Java applications, and among these tools, some monitoring tools also support monitoring of remote computers (such as jps, jstat). In order to start remote monitoring, you need to use the jstatd tool.

​ The command jstatd is an RMI server program, which acts as a proxy server to establish communication between the local computer and the remote monitoring tool. The jstatd server transfers the local Java application information to the remote computer.

image-20221003140239874

Guess you like

Origin blog.csdn.net/weixin_43811294/article/details/127151936