Blog: bugstack.cn

Precipitation, share, grow, let yourself and others can gain something! 😄

One, foreword

How can you learn if you don't use it?

There is no scene, no appeal, how to learn these seem to use knowledge.

In fact, the best way is to summarize, organize, practice, output, a set of combination down, you will master the knowledge of this series.

The JVM is a stable service, so you don’t need to troubleshoot every day. It’s not like the code you wrote!

But the learning of knowledge is to base you on a higher level, and then have access to more interesting work and technological innovation. If you just learn a few instructions, it’s not that much fun. But do you have enough knowledge to develop a full-link monitoring system that includes a method call’s total time, execution path, parameter information, exception results, GC counts, stack data, generational content, and so on?

Okay, let’s see what this article is about, and then follow the steps of Fu Ge.

2. Interview questions

Thanks for the plane, note! Weekend rest at home boring, has been on the grey JVM virtual machine learning to turn out.

Xie Airplane: Caw… Gung… Hey big brother, this, this JVM virtual machine look what ah.

Interviewer: What? Don’t know where to start? Well, you start with the problem!

Xie Plane: what question point? I just don’t know what I don’t know, and I don’t know what to ask you.

Interviewer: Ah! How can I use the JVM fault handling tool to check what parameters are configured when the JVM starts?

Xie Airplane: This! ? No way!

Interviewer: What are the monitoring instructions that you are familiar with? If I ask you how to count the heap memory, do you know? ?

Thank plane: also don’t know, ha ha ha, seem to know want to see what!

Interviewer: Go ahead, take the questions and sort them out!

Basic troubleshooting tools

1. JPS VM process status

JPS (JVM Process Status Tool), which is similar to the ps command, can list the running VIRTUAL machine processes and display the Main Class (Main Class, The main () function in the name of the class) and the process of Local Virtual Machine unique ID (Local Virtual Machine Identifier, LVMID), similar to the ps – ef | grep Java function.

Although this little guy is not big, and the function is simple. But basically you need to use it to query LVMID to determine which VM process you want to monitor.

The command format

jps [ options ] [ hostid ]

  • Options: options and parameters. Different parameters can output required information
  • Hostid: Remote check

A list of options

options describe
-q Output only the process ID, ignoring the main class information
-l Print the full name of the main class, or print the path by executing the JAR package
-m Prints the arguments passed to the main() function of the main class when the virtual machine process starts
-v Output THE JVM parameters for starting the virtual machine process

1.1 JPS -q: Only process ids are listed

E:\itstack\git\github.com\interview>jps -q
104928
111552
26852
96276
59000
8460
76188
Copy the code

1.2 JPS -l: Displays the full name of the current running class

E:\itstack\git\github.com\interview>jps -l
111552 org/netbeans/Main
26852
96276 org.jetbrains.jps.cmdline.Launcher
59000
62184 sun.tools.jps.Jps
8460 org/netbeans/Main
76188 sun.tools.jstatd.Jstatd
Copy the code
  • The output is much clearer with this command,-lAlso a very common parameter option.

1.3 JPS -m, listing the arguments passed to main()

E:\itstack\git\github.com\interview>jps -m
111552 Main --branding visualvm --cachedir C:\Users\xiaofuge\AppData\Local\VisualVM\Cache/8u131 --openid 3041391569375200
26852
96276 Launcher C:/Program Files/JetBrains/IntelliJ IDEA 2019.31./plugins/java/lib/javac2.jar; C:/Program Files/JetBrains/IntelliJ IDEA2019.31./plugins/java/lib/aether-api-1.1. 0.jar; C:/Program Files/JetBrains/IntelliJ IDEA2019.31./lib/jna-platform.jar; C:/Program Fi les/JetBrains/IntelliJ IDEA2019.31./lib/guava-27.1-jre.jar; C:/Program Files/JetBrains/IntelliJ IDEA2019.31./lib/httpclient-4.510..jar; C:/Program Files/JetBrains/IntelliJ IDEA2019.31./lib/forms-1.1-preview.jar; C:/Program Files/JetBrains/IntelliJ IDEA2019.31./plu
gins/java/lib/aether-connector-basic-1.1. 0.jar; C:/Program Files/JetBrains/IntelliJ IDEA2019.31./plugins/java/lib/maven-model-builder-3.39..jar; C:/Program Files/JetBrains/IntelliJ IDEA2019.31./lib/jps-model.jar; C:/Program Files/JetBrains/IntelliJ IDEA2019.31./plu
gins/java/lib/maven-model-3.39..jar; C:/Program Files/JetBrains/IntelliJ IDEA2019.31./plugins/java/lib/aether-impl-1.1. 0.jar; C:/Program Files/JetBrains/IntelliJ IDEA2019.31./lib/gson-2.8. 5.jar; C:/Program File59000
16844 Jps -m
8460 Main --branding visualvm --cachedir C:\Users\xiaofuge\AppData\Local\VisualVM\Cache/8u131 --openid 3041414336579200
76188 Jstatd
Copy the code

1.4 JPS -v, output JVM parameters when vm processes start [-xMS24m -XMx256m]

E:\itstack\git\github.com\interview>jps -v
111552 Main -Xms24m -Xmx256m -Dsun.jvmstat.perdata.syncWaitMs=10000 -Dsun.java2d.noddraw=true -Dsun.java2d.d3d=false -Dnetbeans.keyring.no.master=true -Dplugin.manager.install.global=false --add-exports=java.desktop/sun.awt=ALL-UNNAMED --add-exports=jdk.jvmstat/sun
.jvmstat.monitor.event=ALL-UNNAMED --add-exports=jdk.jvmstat/sun.jvmstat.monitor=ALL-UNNAMED --add-exports=java.desktop/sun.swing=ALL-UNNAMED --add-exports=jdk.attach/sun.tools.attach=ALL-UNNAMED --add-modules=java.activation -XX:+IgnoreUnrecognizedVMOptions -Djdk.
home=C:/Program Files/Java/jdk18.. 0 _161 -Dnetbeans.home=C:\Program Files\Java\jdk18.. 0 _161\lib\visualvm\platform -Dnetbeans.user=C:\Users\xiaofuge1\AppData\Roaming\VisualVM\8u131 -Dnetbeans.default_userdir_root=C:\Users\xiaofuge1\AppData\Roaming\VisualVM -XX:+H
eapDumpOnOutOfMemoryError -XX:HeapDumpPath=C:\Users\xiaofuge1\AppData\Roaming\VisualVM\8u131\var\log\heapdump.hprof -Dsun.awt.keepWorkingSetOnMinimize=true -Dnetbeans.dirs=C:\Program Files\Java\jdk18.. 0 _161\lib\visualvm\visualvm; C:\Program59000  -Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:MaxPermSize=256m
76188Jstatd -Denv.class.path=.; C:\Program Files\Java\jre18.. 0 _161\lib; C:\Program Files\Java\jre18.. 0 _161\lib\tool.jar; -Dapplication.home=C:\Program Files\Java\jdk18.. 0 _161 -Xms8m -Djava.security.policy=jstatd.all.policy
Copy the code

1.5 jps-lv 127.0.0.1: Displays remote machine information

JPS link remote output JVM information, need to register RMI, otherwise error RMI Registry not available at 127.0.0.1.

Add a file named jstatd.all.policy to your C: Program Files\Java\jdk1.8.0_161\bin directory. No other suffixes

The contents of the jstatd.all.policy file are as follows:

grant codebase "file:${java.home}/.. /lib/tools.jar" {
   permission java.security.AllPermission;
};
Copy the code

After the configuration file is added, register the added jstatd.all.policy file in the bin directory: C: \ Program Files \ Java \ jdk1.8.0 _161 \ bin > jstatd – J – Djava. Security policy = jstatd. All. The policy

With luck, you can now view the original machine JVM information as follows:

E:\itstack\git\github.com\interview>jps -l 127.0. 01.
111552 org/netbeans/Main
26852
96276 org.jetbrains.jps.cmdline.Launcher
36056 sun.tools.jps.Jps
59000
8460 org/netbeans/Main
76188 sun.tools.jstatd.Jstatd
Copy the code
  • You can also use a combination of JPS option parameters, such as:The JPS - lm 127.0.0.1

2. Run the JCMD VM diagnostic command

JCMD, a new jm-related diagnostic tool released starting with jdk1.7, can be used to export heap and thread information, view Java processes, perform GC, and perform sample analysis (the flight recorder of the JMC tool). Note that it can only be used on the same sever as the JVM being diagnosed and has the same users and groups.

The command format

jcmd <pid | main class> <command ... |PerfCounter.print|-f file>

  • Pid: ID of the process that receives diagnostic command requests
    • Main class, the main class of the process that receives diagnostic command requests.
  • Command, the main class of the process that receives diagnostic command requests.
  • Perfcounter. print, which prints the performance counters available on the target Java process.
  • -f file reads commands from file and invokes them on the target Java process.
  • -l: displays the list of all processes.
  • -h, -help: displays the help information.

2.1 JCMD pid vm. flags, check the JVM startup parameters

E:\itstack\git\github.com\interview>jcmd 111552 VM.flags
111552:
-XX:CICompilerCount=4 -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=C:\Users\xiaofuge1\AppData\Roaming\VisualVM\8u131\var\log\heapdump.hprof -XX:+IgnoreUnrecognizedVMOptions -XX:InitialHeapSize=25165824 -XX:MaxHeapSize=268435456 -XX:MaxNewSize=89128960 -XX:Min
HeapDeltaBytes=524288 -XX:NewSize=8388608 -XX:OldSize=16777216 -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseFastUnorderedTimeStamps -XX:-UseLargePagesIndividualAllocation -XX:+UseParallelGC
Copy the code

2.2 JCMD pid VM. Uptime: Displays the RUNNING duration of the JVM

E:\itstack\git\github.com\interview>jcmd 111552 VM.uptime
111552:
583248.912 s
Copy the code

2.3 JCMD pid perfCounter. print to view parameters related to JVM performance

E:\itstack\git\github.com\interview>jcmd 111552 PerfCounter.print
111552:
java.ci.totalTime=56082522
java.cls.loadedClasses=5835
java.cls.sharedLoadedClasses=0
java.cls.sharedUnloadedClasses=0
java.cls.unloadedClasses=37.Copy the code

2.4 JCMD pid GC.class_histogram, view the statistical information of classes in the system

E:\itstack\git\github.com\interview>jcmd 111552 GC.class_histogram
111552:

 num     #instances         #bytes  class name-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - 1:50543, 3775720 [C
   2:          3443        2428248  [I3:50138 1203312java.lang.String4:25351 811232java.util.HashMap$Node
   5:          6263         712208  java.lang.Class
   6:          3134         674896  [B
   7:          6687         401056  [Ljava.lang.Object;
   8:          2468         335832  [Ljava.util.HashMap$Node;
Copy the code

2.5 JCMD pid thread. print To view the Thread stack information

E:\itstack\git\github.com\interview>jcmd 111552 Thread.print
111552:
2021-01-10 23:31:13
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.161-b12 mixed mode):

"Computes values in handlers" #52 daemon prio=5 os_prio=0 tid=0x0000000019839000 nid=0x16014 waiting for monitor entry [0x0000000026bce000]
   java.lang.Thread.State: BLOCKED (on object monitor)
        at com.sun.tools.visualvm.core.model.ModelFactory.getModel(ModelFactory.java:76)
        - waiting to lock <0x00000000f095bcf8> (a com.sun.tools.visualvm.jvmstat.application.JvmstatApplication)
        at com.sun.tools.visualvm.application.jvm.JvmFactory.getJVMFor(JvmFactory.java:45)
        at com.sun.tools.visualvm.application.options.Open.openApplication(Open.java:108)
        at com.sun.tools.visualvm.application.options.Open.process(Open.java:93)
        at org.netbeans.spi.sendopts.Option$1.process(Option.java:348)
        at org.netbeans.api.sendopts.CommandLine.process(CommandLine.java:278)
        at org.netbeans.modules.sendopts.HandlerImpl.execute(HandlerImpl.java:23)
        at org.netbeans.modules.sendopts.Handler.cli(Handler.java:30)
        at org.netbeans.CLIHandler.notifyHandlers(CLIHandler.java:195)
        at org.netbeans.core.startup.CLICoreBridge.cli(CLICoreBridge.java:43)
        at org.netbeans.CLIHandler.notifyHandlers(CLIHandler.java:195)
        at org.netbeans.CLIHandler$Server$1ComputingAndNotifying.run(CLIHandler.java:1176)
Copy the code

2.6 JCMD pid VM. System_properties to view JVM system parameters

E:\itstack\git\github.com\interview>jcmd 111552 VM.system_properties
111552:
#Sun Jan 13 23:33:19 CST 2021
java.vendor=Oracle Corporation
netbeans.user=C\:\\Users\\xiaofuge1\\AppData\\Roaming\\VisualVM\\8u131
sun.java.launcher=SUN_STANDARD
sun.management.compiler=HotSpot 64-Bit Tiered Compilers
netbeans.autoupdate.version=1.23
os.name=Windows 10
Copy the code

2.7 JCMD pid Gc. heap_dump path to export the heap dump file

E:\itstack\git\github.com\interview>jcmd 111552 GC.heap_dump C:\Users\xiaofuge1\Desktop\_dump_0110
111552:
Heap dump file created
Copy the code
  • The exported files need to be viewed with JVisualVM

2.8 JCMD PID help, which lists the operations that can be performed

E:\itstack\git\github.com\interview>jcmd 111552 help
111552:
The following commands are available:
JFR.stop
JFR.start
JFR.dump
JFR.check
Copy the code

2.9 JCMD pid help jfr. stop to view the command usage

E:\itstack\git\github.com\interview>jcmd 111552 help JFR.stop
111552:
JFR.stop
Stops a JFR recording

Impact: Low

Permission: java.lang.management.ManagementPermission(monitor)

Syntax : JFR.stop [options]

Options: (options must be specified using the <key> or <key>=<value> syntax)
        name : [optional] Recording name,.e.g \"My Recording\" (STRING, no default value) recording : [optional] Recording number, see JFR.check for a list of available recordings (JLONG, -1) discard : [optional] Skip writing data to previously specified file (if any) (BOOLEAN, false) filename : [optional] Copy recording data to file, e.g. \"C:\Users\user\My Recording.jfr\" (STRING, no default value) compress : [optional] GZip-compress "filename" destination (BOOLEAN, false)
Copy the code

3. Jinfo Java configuration information tool

Jinfo (Configuration Info for Java) allows you to view and adjust JVM parameters in real time.

In the JPS -v command, you can see that it prints out the list of explicit vm startup parameters, but if you want to see a specific parameter more clearly or if you want to know the parameters that are not explicitly specified, you can use jinfo-flag to query.

The command format

jinfo [ option ] pid

use

E:\itstack\git\github.com\interview>jinfo -flag MetaspaceSize 111552
-XX:MetaspaceSize=21807104

E:\itstack\git\github.com\interview>jinfo -flag MaxMetaspaceSize 111552
-XX:MaxMetaspaceSize=18446744073709486080

E:\itstack\git\github.com\interview>jinfo -flag HeapDumpPath 111552
-XX:HeapDumpPath=C:\Users\xiaofuge\AppData\Roaming\VisualVM\8u131\var\log\heapdump.hprof
Copy the code
  • You can query various JVM parameters, which makes it easier to display only the ones you want.

4. Jstat collects VM running data

Jstat (JVM Statistics Monitoring Tool) is used to monitor vm running status information. It can view runtime data such as class loading, memory, garbage collection, and just-in-time compilation in local or remote virtual machine processes.

The command format

jstat -<option> [-t] [-h<lines>] <vmid> [<interval> [<count>]]

  • Vmid: If you want to view remote machines, the following format is required:[protocol:][//]lvmid[@hostname[:port]/servername]
  • Interval and count indicate the query interval and number of times. For example, gc collection of process IDS is queried once every 1000 ms and five times each time.jstat -gc 111552 1000 5

A list of options

options describe
-class Monitor class loading, unload number, total space, and time taken for class loading
-gc Monitor the Java heap, including Eden area, 2 Survivor areas, old age, permanent generation or JDK1.8 meta space, capacity, used space, total garbage collection time, etc
-gccapacity The monitoring is basically the same as -GC, but the output focuses on the maximum and minimum space used by each region of the Java heap
-gcutil The monitoring is basically the same as -GC, but the output focuses on the percentage of total space used
-gccause The same function as -gcutil, but with an additional output of the cause of the last garbage collection
-gcnew Monitor new generation garbage collection
-gcnewcapacity The monitoring content is basically the same as -gcnew, with the output focusing on the maximum and minimum space used
-gcold Monitor old age garbage collection
-gcoldcapacity The monitoring content is basically the same as -gcold, with the output focusing on the maximum and minimum space used
-compiler Outputs information about methods compiled by the just-in-time compiler, time taken, and so on
-printcompilation Outputs methods that have been compiled on the fly
-gcpermcapacity Jdk1.7 and below, permanent generation space statistics
-gcmetacapacity Jdk1.8, meta-space statistics
  • There are a number of monitoring options available for Jstat, but these are the most commonly used.

4.01 jstat-class, class loading statistics

E:\itstack\git\github.com\interview>jstat -class 111552
Loaded  Bytes  Unloaded  Bytes     Time
  5835 12059.6       37    53.5       3.88
Copy the code
  • Loaded, the number of classes Loaded
  • Bytes: indicates the space occupied
  • Unloaded: Number of Unloaded
  • Bytes: indicates the space occupied by the load
  • Time: Time

4.02 jstat -compiler, compiler statistics

E:\itstack\git\github.com\interview>jstat -compiler 111552
Compiled Failed Invalid   Time   FailedType FailedMethod
    3642      0       0     5.61          0
Copy the code
  • Compiled: indicates the number of compilations
  • Failed: indicates the number of failures
  • Invalid: unavailable quantity
  • Time: Time
  • FailedType: indicates the failure type
  • FailedMethod: indicates the FailedMethod

4.03 Jstat-GC, garbage collection statistics

E:\itstack\git\github.com\interview>jstat -gc 111552
 S0C    S1C    S0U    S1U      EC       EU        OC         OU       MC     MU    CCSC   CCSU   YGC     YGCT    FGC    FGCT     GCT
1024.0 512.0   0.0    0.0   77312.0    35.1    39424.0    13622.9   37120.0 34423.3 5376.0 4579.4     60    0.649  52      3.130    3.779
Copy the code
  • S0C, S1C, first and second survival zone sizes
  • S0U, S1U, first and second surviving zone usage sizes
  • EC, EU, size and use of Eden
  • OC, OU, size and use of old age
  • MC, MU, method area size and usage
  • CCSC, CCSU, compress class space size and use
  • YGC, YGCT, garbage collection times and time consumption of young generation
  • FGC, FGCT, garbage collection times and time consuming in old years
  • GCT, total garbage collection time

4.04 jstat-gccapacity, heap memory statistics

E:\itstack\git\github.com\interview>jstat -gccapacity 111552
 NGCMN    NGCMX     NGC     S0C   S1C       EC      OGCMN      OGCMX       OGC         OC       MCMN     MCMX      MC     CCSMN    CCSMX     CCSC    YGC    FGC
  8192.0  87040.0  80384.0 1024.0  512.0  77312.0    16384.0   175104.0    39424.0    39424.0      0.0 1081344.0  37120.0      0.0 1048576.0   5376.0     60    52
Copy the code
  • NGCMN, NGCMX, the minimum and maximum capacity of Cenozoic
  • NGC, current generation capacity
  • S0C, S1C, first and second survival zone sizes
  • EC, the size of Eden Park
  • OGCMN, OGCMX, old age minimum and maximum capacity
  • OGC, OC, current age size
  • MCMN and MCMX, the minimum and maximum capacity of metadata space
  • MC, the size of the current meta space
  • CCSMN, CCSMX, compress class minimum and maximum space
  • YGC, number of GC in the young generation
  • FGC, number of GC in old years

4.05 jstat -gcnewcapacity: displays memory statistics of the new generation

E:\itstack\git\github.com\interview>jstat -gcnewcapacity 111552
  NGCMN      NGCMX       NGC      S0CMX     S0C     S1CMX     S1C       ECMX        EC      YGC   FGC
    8192.0    87040.0    80384.0  28672.0   1024.0  28672.0    512.0    86016.0    77312.0    60    52
Copy the code
  • NGCMN, NGCMX, the minimum and maximum capacity of Cenozoic
  • NGC, current generation capacity
  • S0CMX, the maximum size of the surviving 0 zone
  • S0C, the size of the current surviving 0 region
  • S1CMX, maximum surviving zone 1 size
  • S1C, the current size of surviving zone 1
  • ECMX, maximum Eden park size
  • EC, current Eden park size
  • YGC, garbage collection times of young generation
  • FGC, number of recycling in old years

4.06 Jstat-gcnew, New generation garbage recycling statistics

E:\itstack\git\github.com\interview>jstat -gcnew 111552
 S0C    S1C    S0U    S1U   TT MTT  DSS      EC       EU     YGC     YGCT
1024.0  512.0    0.0    0.0  3  15  512.0  77312.0     70.2     60    0.649
Copy the code
  • S0C, S1C, first and second survival zone sizes
  • S0U, S1U, for the first and second surviving zones
  • TT, the number of times an object survived in the Cenozoic era
  • MTT, the maximum number of times an object survived in the Cenozoic era
  • DSS: The expected size of the surviving zone
  • EC, the size of Eden Park
  • EU, Eden Park use
  • YGC, garbage collection times of young generation
  • YGCT, waste collection time of young generation

4.07 Jstat-gcold, Old garbage collection statistics

E:\itstack\git\github.com\interview>jstat -gcold 111552
   MC       MU      CCSC     CCSU       OC          OU       YGC    FGC    FGCT     GCT
 37120.0  34423.3   5376.0   4579.4     39424.0     13622.9     60    52    3.130    3.779
Copy the code
  • MC, MU, method area size and usage
  • CCSC, CCSU, compress class space size and use
  • OC, OU, old age size and usage
  • YGC, garbage collection times of young generation
  • FGC, the number of garbage collections in the old years
  • FGCT, old garbage collection time
  • GCT, total garbage collection time

4.08 jstat -gcoldcapacity: indicates memory statistics of the old age

E:\itstack\git\github.com\interview>jstat -gcoldcapacity 111552
   OGCMN       OGCMX        OGC         OC       YGC   FGC    FGCT     GCT
    16384.0    175104.0     39424.0     39424.0    60    52    3.130    3.779
Copy the code
  • OGCMN, OGCMX, old age minimum and maximum capacity
  • OGC, current age size
  • OC, old age size
  • YGC, garbage collection times of young generation
  • FGC, the number of garbage collections in the old years
  • FGCT, old garbage collection time
  • GCT, total waste recycling consumption time

4.09 jstat -gcmetacapacity, meta-space statistics

E:\itstack\git\github.com\interview>jstat -gcmetacapacity 111552
   MCMN       MCMX        MC       CCSMN      CCSMX       CCSC     YGC   FGC    FGCT     GCT
       0.0  1081344.0    37120.0        0.0  1048576.0     5376.0    60    52    3.130    3.779
Copy the code
  • MCMN, MCMX, the minimum and maximum capacity of the meta space
  • MC, the current metadata space size
  • CCSMN, CCSMX, compress class minimum and maximum space
  • CCSC, compress class space size
  • YGC, garbage collection times of young generation
  • FGC, the number of garbage collections in the old years
  • FGCT, old garbage collection time
  • GCT, total waste recycling consumption time

4.10 Jstat-gcutil, garbage collection statistics

E:\itstack\git\github.com\interview>jstat -gcutil 111552
  S0     S1     E      O      M     CCS    YGC     YGCT    FGC    FGCT     GCT
  0.00   0.00   0.09  34.55  92.74  85.18     60    0.649    52    3.130    3.779
Copy the code
  • S0, S1, surviving zone 1 and zone 2, current usage ratio
  • E, Proportion of Eden Park
  • O, the proportion of old age area
  • M, proportion of metadata area usage
  • CCS, compression class usage ratio
  • YGC, garbage collection times of young generation
  • FGC, the number of garbage collections in the old years
  • FGCT, old garbage collection time
  • GCT, total waste recycling consumption time

4.11 Jstat-printcompilation, JVM compilation method statistics

E:\itstack\git\github.com\interview>jstat -printcompilation 111552
Compiled  Size  Type Method
    3642      9    1 java/io/BufferedWriter min
Copy the code
  • Compiled: Indicates the number of recently Compiled methods
  • Size: the number of bytecodes in the most recently compiled method
  • Type: the compile Type of the most recently compiled method
  • Method: identifies the Method name

5. Jmap memory mapping tool

Jmap (Memory Map for Java) is used to generate heapdump snapshots.

In addition to getting heap dump snapshots, JMap can also query finalize execution queue, Java heap, and method area details.

The command format

jmap [ option ] pid

  • Option: indicates the option parameter
  • Pid: indicates the ID of the process whose configuration information needs to be printed
  • Executable: generates a Java executable for core dump
  • Core: the core file whose configuration information needs to be printed
  • Server-id: unique ID. If multiple debugging servers are running on the same remote host, use this parameter to identify the server
  • Remote server IP or hostname: indicates the IP address or hostname of the remote debugging server

A list of options

options describe
-dump Generate a Java heap dump snapshot.
-finalizerinfo Displays objects in the F-queue waiting for the Finalizer thread to execute the Finalize method. Linux platform
-heap Displays Java heap details, such as which collector is used, parameter configuration, and generation. Linux platform
-histo Displays heap object statistics, including classes, number of instances, and total capacity
-permstat Display permanent generation memory status, JDk1.7, permanent generation
-F If the VM process does not respond to the -dump option, you can force a snapshot to be generated. Linux platform

5.1 JMAP: Prints the shared object mapping

E:\itstack\git\github.com\interview>jmap 111552
Attaching to process ID 111552, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 25.161-b12
0x000000005b4a0000      1632K   C:\Program Files\Java\jdk18.. 0 _161\jre\bin\awt.dll
0x000000005b8c0000      264K    C:\Program Files\Java\jdk18.. 0 _161\jre\bin\t2k.dll
0x000000005b910000      284K    C:\Program Files\Java\jdk18.. 0 _161\jre\bin\fontmanager.dll
0x000000005b960000      224K    C:\Program Files\Java\jdk18.. 0 _161\jre\bin\splashscreen.dll
0x000000005b9a0000      68K     C:\Program Files\Java\jdk18.. 0 _161\jre\bin\nio.dll
Copy the code

5.2 Jmap-heap, heap details

E:\itstack\git\github.com\interview>jmap -heap 111552
Attaching to process ID 111552, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 25.161-b12

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

Heap Configuration:
   MinHeapFreeRatio         = 0
   MaxHeapFreeRatio         = 100
   MaxHeapSize              = 268435456 (256.0MB)
   NewSize                  = 8388608 (8.0MB)
   MaxNewSize               = 89128960 (85.0MB)
   OldSize                  = 16777216 (16.0MB)
   NewRatio                 = 2
   SurvivorRatio            = 8
   MetaspaceSize            = 21807104 (20.796875MB)
   CompressedClassSpaceSize = 1073741824 (1024.0MB)
   MaxMetaspaceSize         = 17592186044415 MB
   G1HeapRegionSize         = 0 (0.0MB)
Copy the code

5.3 JMAP-clSTATS, print loaded classes

E:\itstack\git\github.com\interview> jmap -clstats 111552
Attaching to process ID 111552, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 25.161-b12
finding class loader instances.done.
computing per loader stat.done.
please wait.computing liveness.liveness analysis may be inaccurate.class_loader    classes bytes   parent_loader   alive?  type

<bootstrap> 3779, 6880779,null          live    <internal>
0x00000000f03853b857, 132574x00000000f031aac8      live    org/netbeans/StandardModule$OneModuleClassLoader@ 0x00000001001684f0
0x00000000f01b9b98      0       0       0x00000000f031aac8      live    org/netbeans/StandardModule$OneModuleClassLoader@ 0x00000001001684f0
0x00000000f005b280      0       0       0x00000000f031aac8      live    java/util/ResourceBundle$RBClassLoader@ 0x00000001000c6ae0
0x00000000f01dfa98      0       0       0x00000000f031aac8      live    org/netbeans/StandardModule$OneModuleClassLoader@ 0x00000001001684f0
0x00000000f01ec51879, 252894,x00000000f031aac8      live    org/netbeans/StandardModule$OneModuleClassLoader@ 0x00000001001684f0
Copy the code

5.4 jmap-dump: indicates heap dump files

E:\itstack\git\github.com\interview>jmap -dump:live,format=b,file=C:/Users/xiaofuge/Desktop/heap.bin 111552
Dumping heap to C:\Users\xiaofuge\Desktop\heap.bin ...
Heap dump file created
Copy the code

6. Jhat Heap dump snapshot analysis tool

Jhat (JVM Heap Analysis Tool) is used in conjunction with JMAP to analyze Heap dump snapshots generated by JMAP.

Jhat has a small HTTP/Web server built in that displays the results of heap dump snapshot analysis in a browser. But it’s not very useful, and most people use other third-party tools.

The command format

jhat [-stack <bool>] [-refs <bool>] [-port <port>] [-baseline <file>] [-debug <int>] [-version] [-h|-help] <file>

Command to use

E:\itstack\git\github.com\interview>jhat -port 8090 C:/Users/xiaofuge1/Desktop/heap.bin
Reading from C:/Users/xiaofuge1/Desktop/heap.bin...
Dump file created Wed Jan 13 16:53:47 CST 2021
Snapshot read, resolving...
Resolving 246455 objects...
Chasing references, expect 49 dots.................................................
Eliminating duplicate references.................................................
Snapshot resolved.
Started HTTP server on port 8090
Server is ready.
Copy the code

http://localhost:8090/

7. Jstack Java stack tracing tool

Jstack (Stack Trace for Java) is used to generate thread snapshots (threaddump and Javacore) of the VM at the current time.

A thread snapshot is a collection of method stacks that are being executed by each thread in a VM. The purpose of a thread snapshot is to locate the cause of a thread’s long pause, such as thread deadlock, dead loop, and suspension caused by a long time to request external resources.

When a thread appears, you can look at the call stack of each thread through JStack to see what the heck is going on with the non-responding thread.

The command format

jstack [ option ] vmid
Copy the code

Option parameters

options describe
-F Forces the output thread stack when a normally output request is not responded to
-l Displays additional information about locks in addition to the stack
-m A C/C ++ stack can be displayed if a native method is called

Command to use

E:\itstack\git\github.com\interview>jstack 111552
2021-01-10 23:15:03
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.161-b12 mixed mode):

"Inactive RequestProcessor thread [Was:StdErr Flush/org.netbeans.core.startup.logging.PrintStreamLogger]" #59 daemon prio=1 os_prio=-2 tid=0x000000001983a800 nid=0x688 in Object.wait() [0x0000000017fbf000]
   java.lang.Thread.State: TIMED_WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        at org.openide.util.RequestProcessor$Processor.run(RequestProcessor.java:1939)
        - locked <0x00000000fab31d88> (a java.lang.Object)
Copy the code
  • To verify usage, try writing a thread in an infinite loop and then viewing the thread information through JStack.

Visual troubleshooting tool

1. Jconsole, Java monitoring and management console

Java Monitoring and Management Console (JConsole) is a visual Monitoring and Management tool based on Java Manage-ment Extensions (JMX).

Its function is mainly to collect and adjust the parameters of the system. It can not only be managed in the virtual machine itself but also developed in the software. It is an open service with corresponding code API calls.

JConsole starts

Use JConsole

2. VisualVM, multi-fault processing tool

VisualVM (All-In-one Java Troubleshooting Tool) is One of the most powerful operational monitoring and Troubleshooting tools.

In addition to routine operation monitoring, troubleshooting, it can also do performance analysis and other work. Because of its versatility and low impact on applications, it can be directly plugged into a production environment.

VisualVM IDEA to install

VisualVM USES

public static void main(String[] args) throws InterruptedException {
    
    Thread.sleep(5000);
    ClassLoadingMXBean loadingBean = ManagementFactory.getClassLoadingMXBean();
    while (true) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(MetaSpaceOomMock.class);
        enhancer.setCallbackTypes(new Class[]{Dispatcher.class, MethodInterceptor.class});
        enhancer.setCallbackFilter(new CallbackFilter() {
            @Override
            public int accept(Method method) {
                return 1;
            }
            @Override
            public boolean equals(Object obj) {
                return super.equals(obj); }}); System.out.println(enhancer.createClass().getName() + loadingBean.getTotalLoadedClassCount() + loadingBean.getLoadedClassCount() + loadingBean.getUnloadedClassCount()); }}Copy the code

Remember to adjust the metascale

-XX:MetaspaceSize=8m
-XX:MaxMetaspaceSize=80m
-Djava.rmi.server.hostname=127.0. 01.
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=7397
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false
Copy the code
  • We’re going to monitor this piece of code that’s causing the metaspace to overflow,java.lang.OutOfMemoryError: Metaspace

Monitoring results

Five, the summary

  • This article is also a summary of the process of learning “Deep understanding of Java Virtual Machine”, which includes a lot of common instructions, through the learning of these instructions we will probably know what kind of monitoring information the JVM provides to us.
  • In fact, the actual business use is rarely to monitor the JVM through instructions, but there is a whole set of non-invasive full link monitoring, monitoring in the monitoring service along with the JVM at the time of the method call, allowing developers to troubleshoot problems more quickly. However, the implementation of these tools still needs these foundations. After mastering the basic knowledge, you can better use the tools.
  • The study of programming technical knowledge must be verified by practice, otherwise it is easy to forget and difficult to master. When you go through your own hand more than a few times later, there will be a completely different understanding. All right, come on! Hopefully this article will give you a boost!

Six, series recommendation

  • To figure out class loading, hand lift the JVM!
  • Summary of JVM memory model, there are various versions of JDK comparison, there are OOM monitoring cases, there are Java version of virtual machine, integrated learning easier!
  • Core knowledge of HashMap, disturbance function, load factor, expansion linked list resolution, deep learning
  • Recognize your technology stack blind spots
  • Introduction and use of thread pool, and design of non-intrusion monitoring based on JVMTI