1 Introduction to VM tools
System positioning problem: knowledge and experience is the basis, data is the basis, tools are the means of using knowledge to process books. D: Program Files\Java\jdk1.8.0_92\bin\ JPS,jstat,jstack and other tools are small because they reference the tools.jar package (D:\Program) Files\Java\jdk1.8.0_92\lib\tools.jar). Jar \sun\tools\ JPS,jstat,jstack, etc
2 Vm tool-JPS details
C:\Users\bob>jps -help;
illegal argument: -help;
usage: jps [-help]
jps [-q] [-mlvV] [<hostid>]
Definitions:
<hostid>: <hostname>[:<port>]
Copy the code
2.1 the JPS
Java Process Status Displays the unique ID of the local VM (LVMID. local Virtual Machine ID).
C:\Users\ Bob > JPS 12256 Launcher 12336 JPS // itself is a process 11000 // open IDEA, i.e. PID, 13948 RemoteMavenServerCopy the code
If you run the main program, you can also see the process through JPS. Such as:
12345 Main
12346 Main
Copy the code
2.2 the JPS – l
Display the full class method or JAR file
The JPS – 2.3 m
Run the program arguments accepted by the main class (program Arguments configured in Eclipse or IEDA)
2.4 the JPS – v
Run JVM arguments accepted by the main class (VM arguments in Eclipse and VM Options in IDEA)
Home =D:\Program Files\Java\ jdk1.8.0_92-xMS8m C:\Users\bobshute> JPS -v 10900 -Xms128m -Xmx750m -XX:ReservedCodeCacheSize=240m -XX:+UseConcMarkSweepGC -XX:SoftRefLRUPolicyMSPerMB=50 -ea -Dsun.io.useCanonCaches=false -Djava.net.pref erIPv4Stack=true -XX:+HeapDumpOnOutOfMemoryError XX: - OmitStackTraceInFastThrow - Djb. VmOptionsFile = D: \ ideaIU - 2017.3.1 win (1) \ bin \ idea64 exe. Vmoptions - Xbootclas Spath/a: D: \ ideaIU - 2017.3.1 win (1) \ lib \ boot jar - Didea. Jre. Check = true - Didea. Path s.s elector = IntelliJIdea2017.3 -XX:ErrorFile=C:\Users\bobshute\java_error_in_idea_%p .log -XX:HeapDumpPath=C:\Users\bobshute\java_error_in_idea.hprof 10808 RemoteMavenServer - Djava. Awt. Headless = true - Didea. Version = = 2017.3.1-8 m - Didea Xmx76. Maven embedder. Version = 3.3.9 - Dfile. GBK encoding = 10620 - Dosgi. RequiredJavaVersion = 1.8 - Xms40m - Dosgi. Module. Lock. The timeout = 10 - Xve rify: none - Dorg. Eclipse SWT. Browser. IEVersion = 10001-4556 the Jps Xmx1200m - Dapplication. Home = D: \ \ Program Files \ Java \ jdk1.8.0 _92 - Xms8mCopy the code
Where 10900 is IDEA; 10620 for eclipse.
2.5 the JPS – LMV
Multiple arguments can be used together.
3 VM tool – Jstat details
3.1 introduction
Information on class loading, memory, garbage collection, and JIT compilation
Jstat is a lightweight widget that comes with the JDK. Java Virtual Machine Statistics Monitoring Tool is located in the Bin directory of Java. It mainly uses JVM built-in instructions to monitor the resources and performance of Java applications on the command line in real time. Monitoring of Heap size and garbage collection status is included. As you can see, Jstat is a lightweight, JVM-specific tool that works just fine.
The Jstat tool is particularly powerful, with numerous options to look in detail at how much each part of the heap is being used and how many classes are being loaded. To use this command, add the id of the process to view the process and the selected parameters. The reference format is as follows:
C:\Users\bobshute>jstat -help
invalid argument count
Usage: jstat -help|-options
jstat -<option> [-t] [-h<lines>] <vmid> [<interval> [<count>]]
Definitions:
<option> An option reported by the -options option
<vmid> Virtual Machine Identifier. A vmid takes the following form:
<lvmid>[@<hostname>[:<port>]]
Where <lvmid> is the local vm identifier for the target
Java virtual machine, typically a process id; <hostname> is
the name of the host running the target Java virtual machine;
and <port> is the port number for the rmiregistry on the
target host. See the jvmstat documentation for a more complete
description of the Virtual Machine Identifier.
<lines> Number of samples between header lines.
<interval> Sampling interval. The following forms are allowed:
<n>["ms"|"s"]
Where <n> is an integer and the suffix specifies the units as
milliseconds("ms") or seconds("s"). The default units are "ms".
<count> Number of samples to take before terminating.
-J<flag> Pass <flag> directly to the runtime system.
C:\Users\bobshute>
Copy the code
Jstat-options can list the options supported by the current JVM version. Compiler (JIT) GCcapacity gCCause gcnew gcnewCapacity Gcold gcoldCapacity gcpermCapacity gcutil printcompilationCopy the code
Jstat-gccause: Outputs the reason for the last GC in addition
3.2 GC statistics summary
Jstat [- command options] [vmID (process number)] [Interval/ms] [number of queries]
Jstat -gcutil 6692 1000 10 Print 10 times every 1000ms
C:\Users\bobshute>jstat -gcutil 10004 S0 S1 E O M CCS YGC YGCT FGC FGCT GCT 0.00 99.82 25.88 74.20 90.28 80.46 41 1.498 8 2.299 3.77 C:\Users\bobshute> S0:Survivor0 S2:Survivor1 E:Eden O:old space M:metaspace METAspace CCS:Compressed class space YGC: Number of young generation garbage collection events. -gc option garbage-collected heap statistics. S0C: Current survivor space 0 capacity (kB).s1c: Current survivor space 1 capacity (kB). S0U: Survivor space 0 utilization (kB). S1U: Survivor space 1 utilization (kB). EC: Current eden space capacity (kB). EU: Eden space utilization (kB). OC: Current old space capacity (kB). OU: Old space utilization (kB). MC: Metaspace capacity (kB). MU: Metacspace utilization (kB). CCSC: Compressed class space capacity (kB). CCSU: Compressed class space used (kB). YGC: Number of young generation garbage collection events. YGCT: Young generation garbage collection time. FGC: Number of full GC events. FGCT: Full garbage collection time. GCT: Total garbage collection time.Copy the code
3.3 Class loading statistics
C:\Users\bobshute>jstat -class 18036
Loaded Bytes Unloaded Bytes Time
43242 46208.3 273 207.0 66.19
Copy the code
Loaded: The number of Unloaded classes Bytes: the number of Unloaded Spaces Bytes: the space still Unloaded Time: the Time
3.4 Compiling Statistics
C:\Users\bobshute>jstat -compiler 18036 Compiled Failed Invalid Time FailedType FailedMethod 25356 10 108.24 1 com/intellij/openapi/vfs/newvfs/impl /VirtualDirectoryImpl aCopy the code
Compiled: indicates the number of compilations. Failed: Failed quantity Invalid: unavailable quantity Time: Time FailedType: failure type FailedMethod: Failed method
3.5 Garbage collection statistics
C:\Users\ Bobshute >jstat -gc 18036 S0C S1C S0U S1U EC EU OC OU MC MU CCSC CCSU YGC YGCT FGC FGCT GCT 4352.0 4352.0 0.0 1415.1 34944.0 26192.1 197676.0 173809.6 189312.0 182 286.3 0.0 0.0 93 1.064 10 0.348 1.412Copy the code
S0C: size of the first survivable zone S1C: size of the second survivable zone S0U: size of the first survivable zone S1U: size of the second survivable zone EC: size of the Eden zone EU: size of the Eden zone OC: size of the old age OU: size of the old age MC: size of the method zone MU: Method area usage size CCSC: indicates the space size of the compression class. CCSU: indicates the space usage size of the compression class. YGC: indicates the garbage collection times of the young generation
3.6 Heap memory Statistics
C:\Users\bobshute>jstat -gccapacity 18036 NGCMN NGCMX NGC S0C S1C EC OGCMN OGCMX OGC OC MCMN MCMX MC CCSMN CCSMX CCSC YGC FGC 43648.0 174720.0 43648.0 4352.0 4352.0 34944.0 87424.0 349568.0 197676.0 197676.0 0.0 189824.0 189440.0 0.0 0.0 94 10Copy the code
S0C: the size of the first surviving zone S1C: the size of the second surviving zone EC: the size of the Eden Zone OGCMN: the minimum capacity of the old age OGCMX: the maximum capacity of the old age OGC: Current age size OC: current age size MCMN: minimum metadata capacity MCMX: maximum metadata capacity MC: current size of metadata space CCSMN: minimum size of compressed class space CCSMX: maximum size of compressed class space CCSC: current size of compressed class space YGC: FGC: Gc number of the old generation
3.7 New generation garbage recycling statistics
C:\Users\bobshute>jstat -gcnew 18036 S0C S1C S0U S1U TT MTT DSS EC EU YGC YGCT 4352.0 4352.0 0.0 474.0 6 6 2176.0 34944.0 12352.2 1.086 97Copy the code
S0C: size of the first surviving zone S1C: size of the second surviving zone S0U: size of the first surviving zone S1U: size of the second surviving zone TT: number of times the object survives in the Cenozoic MTT: maximum number of times the object survives in the Cenozoic DSS: expected size of the surviving zone EC: size of the Eden zone EU: Usage size of Eden Park YGC: number of garbage collection of young generation YGCT: consumption time of garbage collection of young generation
3.8 Memory Statistics of new generation
C:\Users\bobshute>jstat -gcnewcapacity 18036
NGCMN NGCMX NGC S0CMX S0C S1CMX S1C ECMX
EC YGC FGC
43648.0 174720.0 43648.0 17472.0 4352.0 17472.0 4352.0 139776.0
34944.0 100 10
Copy the code
S0CMX: the size of the largest surviving zone 1 S0C: the size of the largest surviving zone 1 S1CMX: the size of the largest surviving zone 2 S1C: the size of the largest surviving zone 2 ECMX: the size of the largest Eden zone EC: Current size of Eden Park YGC: recycling times of young generation FGC: recycling times of old generation
3.9 Statistics of garbage collection in the old age
C:\Users\bobshute>jstat -gcold 18036 MC MU CCSC CCSU OC OU YGC FGC FGCT GCT 189440.0 182421.0 0.0 197676.0 174628.4 101 10 0.34 8 1.456Copy the code
MC: method area size MU: method area used size CCSC: space used by the compression class CCSU: space used by the compression class OC: space used by the old age OU: space used by the old age YGC: number of garbage collections in the young generation FGC: number of garbage collections in the old age FGCT: time consumed by garbage collection in the old age GCT: Total time spent in garbage collection
3.10 Memory Statistics in the old age
C:\Users\bobshute>jstat -gcoldcapacity 18036
OGCMN OGCMX OGC OC YGC FGC FGCT GCT
87424.0 349568.0 197676.0 197676.0 103 10 0.348 1.468
Copy the code
OGCMN: minimum capacity in the old age OGCMX: maximum capacity in the old age OGC: current size in the old age OC: size in the old age YGC: number of garbage collections in the young generation FGC: number of garbage collections in the old age FGCT: number of garbage collections consumed in the old age GCT: total number of garbage collections consumed in the old age
3.11 Metadata Space Statistics
C:\Users\bobshute>jstat -gcmetacapacity 18036
MCMN MCMX MC CCSMN CCSMX CCSC YGC FGC
FGCT GCT
0.0 189824.0 189440.0 0.0 0.0 0.0 103 10
0.348 1.468
Copy the code
CCSMN: minimum size of the compressed class space CCSMX: maximum size of the compressed class space CCSC: current size of the compressed class space YGC: number of garbage collections in the young generation FGC: number of garbage collections in the old generation FGCT: Old age waste recycling consumption
3.12 Summarize garbage collection statistics
C:\Users\bobshute>jstat -gcutil 18036 S0 S1 E O M CCS YGC YGCT FGC FGCT GCT 3.76 0.00 12.85 88.34 96.30-104 1.127 10 0.348 1.47 5Copy the code
S0: current usage ratio of surviving area 1 S1: current usage ratio of surviving area 2 E: usage ratio of Eden park O: usage ratio of old age M: usage ratio of metadata area CCS: compression usage ratio YGC: garbage collection times of young generation FGC: garbage collection times of old age FGCT: garbage collection time of old age GCT: Total time spent in garbage collection
3.13 STATISTICS on JVM compilation methods
C:\Users\bobshute>jstat -printcompilation 18036
Compiled Size Type Method
25815 109 1 com/intellij/openapi/progress/impl/ProgressManagerImpl$1$$L
ambda$89 run
Copy the code
Compiled: indicates the number of recently Compiled methods Size: indicates the number of bytecode Compiled methods Type: indicates the compilation Type of recently Compiled methods Method: indicates the Method name identifier.
3.14 yuan space
After including 7, the permanent generation disappears and is replaced by the metaclspace (M). Metaclspace is similar in nature to the permanent generation, which is an implementation of the method area in the JVM specification. However, the biggest difference between a meta-space and a permanent generation is that the meta-space is not in the virtual machine, but uses local memory. Therefore, by default, the size of the meta-space is limited only by local memory.
3.15 Reference article
Official description Jstat Command Details how to use the jstat command
4 VM tool -jinfo
4.1 introduction
View and adjust VM parameters in real time. Some commands in jinfo can be executed only in Linux, but not in Windows.
C:\Users\bobshute>jinfo Usage: jinfo [option] <pid> (to connect to running process) jinfo [option] <executable <core> (to connect to a core file) jinfo [option] [server_id@]<remote server IP or hostname> (to connect to remote debug server) where <option> is one of: -flag <name> to print the value of the named VM flag -flag [+|-]<name> to enable or disable the named VM flag -flag <name>=<value> to set the named VM flag to the given value -flags to print VM flags -sysprops to print Java system properties <no option> to print both of the above -h | -help to print this help messageCopy the code
4.2 jinfo – flag
Jinfo-flag UseSerialGC 6574// 6574 Whether the serialGC garbage collector is used by the process
Jinfo-flag UseG1GC 6574 // whether the process 6574 uses the G1GC garbage collector.
C:\Users\bobshute> jinfo-flag UseSerialGC 6312-xx: -useserialgc // -xx indicates the virtual machine parameter, and - indicates that the parameter is not enabled C:\Users\ Bobshute > jinfo-flag UseG1GC 6312-xx :+UseG1GC // -xx for virtual machine parameters,+ for enabled C:\Users\bobshute>Copy the code
Jinfo flag + / – 4.3
Adjust parameters without restarting
jinfo
-flag [+|-]<name> to enable or disable the named VM flag
-flag <name>=<value> to set the named VM flag to the given value
Copy the code
// Add JVM parameters without restart,6312 is the process number C:\Users\bobshute> jinfo-flag +PrintGC 6312-xx: -printgc C:\Users\bobshute> jinfo-flag +PrintGCDetails 6312-xx: -printgc C:\Users\bobshute>jinfo -flag +PrintGCTimeStamps 6312-xx: -printgc // Remove JVM parameters without restarting C:\Users\bobshute>jinfo -flag -PrintGC 6312 -XX:-PrintGCCopy the code
4.4 jinfo – flags
Displays the JVM parameters currently in use
C:\Users\bobshute>jinfo -flags 6312 Attaching to process ID 6312, please wait... Debugger attached successfully. Server Compiler detected. JVM version is 25.92-B14 non-default VM Flags: -XX:-BytecodeVerificationLocal -XX:-BytecodeVerificationRe mote -XX:CICompilerCount=3 -XX:InitialHeapSize=41943040 -XX:MaxHeapSize=12582912 00 -XX:MaxNewSize=419430400 -XX:MinHeapDeltaBytes=524288 -XX:NewSize=13631488 -X X:OldSize=28311552 -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+U seFastUnorderedTimeStamps -XX:-UseLargePagesIndividualAllocation -XX:+UseParalle lGC Command line: - Dosgi. RequiredJavaVersion = 1.8 - Xms40m - Dosgi. Module. Lock. The timeout = 10 - Xverify: none -Dorg.eclipse.swt.browser.IEVersion=10001 -Xmx1200m C:\Users\bobshute>Copy the code
5. Vm tool – JMAP details
5.1 introduction
5.1.1 introduction
The jmap command (Java Memory Map) is mainly used to print the shared object Memory Map or heap Memory details of the specified Java process (or core file, remote debug server). The jmap command takes a snapshot of the heap of a running JVM, allowing you to analyze the heap offline to check for memory leaks, to check for the creation of large objects that have a significant impact on performance, to check what objects are in the system the most, how much memory each object occupies, and so on. Heap dumps can be generated using Jmap.
Java = Direct Memory + JVM Memory (MaxPermSize +Xmx)
Some commands in JMQP can only be executed in Linux, not Windows. Jhat analyzes DUMP information: JHAT is a tool for analyzing JVM HEAP DUMP files in Sun 1.6 and later. It analyzes the memory usage of objects in the JVM HEAP
From the point of view of the safe log, the entire JVM is paused from Heap Dump. Considering I/O, a few gigabytes of Heap may produce pauses of several seconds. Be careful when executing in production.
C:\Users\bobshute>jmap
Usage:
jmap [option] <pid>
(to connect to running process)
jmap [option] <executable <core>
(to connect to a core file)
jmap [option] [server_id@]<remote server IP or hostname>
(to connect to remote debug server)
where <option> is one of:
<none> to print same info as Solaris pmap
-heap to print java heap summary
-histo[:live] to print histogram of java object heap; if the "live"
suboption is specified, only count live objects
-clstats to print class loader statistics
-finalizerinfo to print information on objects awaiting finalization
-dump:<dump-options> to dump java heap in hprof binary format
dump-options:
live dump only live objects; if not specified
,
all objects in the heap are dumped.
format=b binary format
file=<file> dump heap to <file>
Example: jmap -dump:live,format=b,file=heap.bin <pid>
-F force. Use with -dump:<dump-options> <pid> or -histo
to force a heap dump or histogram when <pid> does not
respond. The "live" suboption is not supported
in this mode.
-h | -help to print this help message
-J<flag> to pass <flag> directly to the runtime system
C:\Users\bobshute>
Copy the code
5.1.2 Basic Parameters
- If jMAP is used to print shared object maps without options, the start address, map size, and full path name of each shared object file loaded on the target VM are printed. This is similar to the Solaris Pmap tool.
- -dump:[live,]format=b,file= Outputs the HEAP contents of the JVM to the file using hprof binary format. The live suboption is optional. If live is specified, only live objects are exported to the file.
- – finalizerInfo Prints information about objects that are waiting to be reclaimed.
- -heap Displays the summary information about the heap, the algorithm used by GC, the heap configuration, and the wise Heap usage.
- -histo[:live] Displays the number of instances, memory usage, and full name of each class. The internal class name of the VM is prefixed with “*”. If the live subparameter is added, only the number of live objects is counted.
- -permstat Prints information about classload and JVM heap persistence layers. Contains the name of each classloader, liveliness, address, parent ClassLoader, and number of classes loaded. In addition, the number of internal strings and memory usage is also printed.
- -f force. Use -dump or -histo when pid is not responding. In this mode, the live subparameter is invalid.
- – h | -help printing auxiliary information
- -j passes parameters to jMAP-started JVMS.
- Pid Indicates the ID of the Java process whose phase information needs to be printed. You can use JPS to query the id
5.1.3 Analyzing dump Files
Dump files are recommended to be opened with the VisualVM of JDK or the MAT plug-in of Eclipse. There are two ways to count the size of objects:
Shallow Size: The original Size of the object. Retained Size: the Size of the current object plus the total Size of the objects directly or indirectly referenced by the current object. Jmap-histo :live pid = jmap-histo :live pid = jmap-histo :live pid = jmap-histo :live pid So the concern is to keep large objects and see who is referring to char[], byte[].
(MAT can view more information, but VisualVM is better than the JVM, use the following: jVisualvm command line, file -> load -> heap Dump-> check -> find 20 the largest reserved size of the object, it will trigger the calculation of reserved size, and then you can browse in the class view, by reserved size sort)
5.2 jmap – dump
5.2.1 usage
Example Export heap snapshot information for future analysis
- -live Exports live
- – the format format
- -file File address
C:\Users\bobshute>jmap -dump:format=b,file=d:\a.bin 10492
Dumping heap to D:\a.bin ...
Heap dump file created
C:\Users\bobshute>
Copy the code
5.2.2 Analyzing Memory Leaks OOM common usage
- 1) may also be displayed by the JVM configuration Dump information: – XX: + HeapDumpOnOutOfMemoryError
Have the JVM automatically generate a Dump file when it encounters an OutOfMemoryError
- 2) jmap-dump :format=b,file=/path/heap.bin process ID
If only live objects in the heap are dumped, the option -live is added.
- 3) Then use MAT analysis tools, such as jhat command, eclipse’s MAT plug-in. Finally, install the MAT plug-in in Eclipse (www.eclipse.org/mat/), and then in ec…
Specific operation method: first enter www.eclipse.org/mat/previou… URLhttp://download.eclipse.org/mat/1.1.0/update-site/ Releases “, select Indigo version
5.3 jmap – heap [pid]
It is important to note that in the case of CMS GC, jmap-heap execution can cause JAVA processes to hang
Ps - ef | grep tomcat # for tomcat pid/root @ localhost ~ # jmap - heap 27900 Attaching to the process ID 27900, both please wait... Debugger attached successfully. Client Compiler detected. JVM version is 20.45-B01 using Ththread -local object allocation. Mark Sweep Compact GC Heap Configuration: MinHeapFreeRatio = 40 # -xx :MinHeapFreeRatio = 70 MinHeapFreeRatio = 40 # -xx :MinHeapFreeRatio = 70 # -xx :MaxHeapFreeRatio Set the maximum idle ratio of the JVM heap MaxHeapSize= 100663296 (96.0MB) # -xx :MaxHeapSize= set the maximum idle ratio of the JVM heap NewSize = 1048576 (1.0MB) # -xx :NewSize= Set the default size of the JVM heap 'new generation' MaxNewSize= 4294901760 (4095.9375MB) # -xx :MaxNewSize= set the maximum size of the JVM heap 'new generation' OldSize = 4194304 (4.0MB) # -xx :OldSize= Set JVM heap size NewRatio= 2 # -xx :NewRatio=: size ratio of 'new generation' and 'old generation' SurvivorRatio = 8 # -xx :SurvivorRatio= set SurvivorRatio of the young generation to 12582912 (12.0MB) # -xx :PermSize=<value>: set the initial size of the JVM heap 'persistent generation' MaxPermSize= 67108864 (64.0MB) # -xx :MaxPermSize=<value>: New Generation (Eden + 1 Survivor Space): # Cenozoic memory distribution, Capacity = 30212096 (28.8125MB) Used = 27103784 (25.848182678222656MB) Free = 3108312 Capacity = 30212096 (28.8125MB) Used = 27103784 (25.848182678222656MB) Free = 3108312 89.71169693092462% Used Eden Space: Capacity = 26869760 (25.625MB) Used = 26869760 (25.625MB) Free = 0 (0.0MB) 100.0% Used From Space: Capacity = 3342336 (3.1875MB) Used = 234024 (0.22318267822265625MB) Free = 3108312 (2.9643173217773438MB) 7.001809512867647% Capacity = 3342336 (3.1875MB) used = 0 (0.0MB) Free = 3342336 (3.1875MB) 0.0% used tenured generation: Capacity = 67108864 (64.0MB) Used = 67108816 (63.99995422363281MB) Free = 48 (e-5 MB) 99.99992847442627% informs the Perm Generation: Capacity = 14417920 (13.75MB) Used = 14339216 (13.674942016601562MB) Free = 78704 (0.0750579833984375MB) 99.45412375710227%, informsCopy the code
5.4 jmap histo – 10492
Display number of classes and instances Displays the number of instances of each class, memory usage, and the full name of the class. The internal class name of the VM is prefixed with “*”. If the live subparameter is added, only the number of live objects is counted.
C: \ Users \ bobshute > jmap histo - 10492 shows a lot of * * 10778:1 16 sun. Util. Resources. LocaleData 10779: 1 16 sun.util.resources.LocaleData$LocaleDataRes ourceBundleControl Total 6683308 329071952 // Serial number, Instances (instances), bytes (size), classs name (class name) It's basically in reverse order of usage. #instance = number of instances of the object #bytes = total number of bytes class name = B = byte C = char D = double F = float I Int J stands for long, Z stands for Boolean, preceded by [for array, [I is equivalent to int[]. Objects are represented by [L+ class nameCopy the code
Show that many can see by the grep jmap histo – 10492 | grep/filter/see histo jmap – 10492 | more / / paging
Jmap histo – 5.5: live pid
Jmap-histo :live PID >a.log can observe the condition of all objects in the heap (condition of all objects living in the heap). This includes the number of objects and the amount of space they occupy. You can save it to text, and after a period of time, using the text comparison tool, you can compare which objects the GC reclaimed.
When jmap-histo :live is executed, the JVM triggers GC first and then statistics.
5.6 summarize
- 1. If the program is out of memory or GC is frequent, it is likely that there is a memory leak. In this case, use Java heap Dump to check the status of objects.
- 2. To create heap Dump, you can use jmap directly from the JVM
- 3. Run the jmap-heap command to check the heap usage and the space usage of each heap.
- 4. Use jmap-histo :[live] to view objects in the heap memory. If a large number of objects are continually referenced and not released, then there is a memory leak and the code needs to be combined to release unused objects.
- 5. You can also run the jmap -dump:format=b,file= command to save the heap information to a file, and then run the jhat command to view details
- 6. If memory leaks, overflows, or other conditions occur, you are advised to dump the memory several times and archive the memory files for subsequent memory analysis.
- 7. In CMS GC, executing jmap-heap sometimes causes the process to change T, so it is strongly recommended not to execute this command. To obtain the current usage of each area of memory, you can use jstat -gc or jstat -gccapacity.
5.7 Reference articles (Worth learning)
Java command — Jmap command use (with analysis process)
6. Eclipse Memory Analyzer analysis tool
Eclipse provides a plug-in for analyzing JVM heap Dump files. With this plug-in, you can view the memory usage of objects, reference relationships, analyze memory leaks, and more. www.eclipse.org/mat/
7 Details about vm tool jhat
7.1 basis
Jhat: The JVM Heap Analysis Tool analyzes JVM memory information exported by JMAP. Rarely used because: 1. Occupy CPU and memory during analysis. Therefore, analysis is not performed on the server. 2.
C:\Users\bobshute>jhat d:\a.bin Reading from d:\a.bin... Dump file created Sun Dec 24 15:44:46 CST 2017 Snapshot read, resolving... Resolving 10465204 objects... Chasing references, expect 2093 dots............................................ . . Eliminating duplicate references................................................ . . Snapshot resolved. Started HTTP server on port 7000 Server is ready.Copy the code
It can then be accessed at http://localhost:7000/. The following information is displayed:
All Classes (excluding platform) Package <Arrays> class [Laj.org.objectweb.asm.Attribute; [0xfa909a48] class [Laj.org.objectweb.asm.Item; [0xfcc695d0] class [Laj.org.objectweb.asm.Label; [0xfcc692f8] class [Laj.org.objectweb.asm.Type; [0xfcc69290] class [Lch.qos.logback.core.joran.spi.ConsoleTarget; [0xb7053a98] class [Lch. Qos. Logback. Core. The pattern. The parser. The TokenStream $TokenizerState; xb7053a30 [0]... many... the class scalariform.formatter.preferences.SpacesAroundMultiImports$ [0xb8ace758] class Scalariform. The formatter. Preferences. SpacesWithinPatternBinders $xb8ace478 [0] Other Queries (hereinafter as links can click access) All classes including platform Show all members of the rootset Show instance counts for all classes (including platform) Show instance counts for all classes (excluding platform) Show heap histogram Show finalizer summary Execute Object Query Language (OQL) query http://localhost:7000/oql/, you can query in the page as SQL query object. For example: select the from Java. Lang. The String s where s.v alue. Length > 1000Copy the code
The last link address is: http://localhost:7000/oql/, you can query in the page as SQL query object. For example, select from java.lang.String s where s.value. Length >1000
8 Vm Tool-JStack Description
8.1 introduction
Jstack is a stack tracing tool that comes with the Java VIRTUAL machine. The jstack command is mainly used to view the call stack of Java threads and can be used to analyze thread problems (such as deadlocks). Endless loop). Jstack is used to print the Java process ID or corefile or Java stack information of the remote debug service. On a 64-bit machine, you need to specify the option “-j-d64”. Windows jStack only supports the following methods:
jstack [-l] pid
Copy the code
Mainly divided into two functions: 1). Do local or remote thread dump for live processes. 2). Do thread dump for core files.
Jstack is used to generate a thread snapshot of the Java VIRTUAL machine at the current time. A thread snapshot is a collection of method stacks that are being executed by each thread in the Java VIRTUAL machine (JVM). The main purpose of a thread snapshot is to locate the cause of a long pause in a thread, such as deadlocks, loops, and long waits caused by requests for external resources. By looking at the call stack of each thread when it pauses, you can see what the unresponsive thread is doing in the background, or what resources it is waiting for. If a Java program crashes to generate a core file, the JStack tool can be used to get information about the Java Stack and native stack of the core file, so you can easily know how the Java program crashed and where the problem occurred in the program. In addition, the JStack tool can attach to a running Java program and see information about the Java Stack and native Stack of the running Java program. Jstack is very useful if the current running Java program appears hung.
8.2 Command Formats
C:\Users\bobshute>jstack Usage: jstack [-l] <pid> (to connect to running process) jstack -F [-m] [-l] <pid> (to connect to a hung process) jstack [-m] [-l] <executable> <core> (to connect to a core file) jstack [-m] [-l] [server_id@]<remote server IP or hostname> (to connect to a remote debug server) Options: -f to force a thread dump. Use when jstack <pid> does not respond (process is hung) -m to print both Java and Native frames (mixed mode)// Java and local method stack -l long listing. Prints Additional information about locks// Additional information about locks, such as -h or -help to print this help messageCopy the code
Jstack [option] pid jstack [option] executable core [server-id@] remote-hostname-or-ip // specifies the hostname or IP address of the remote debug service. Server-id specifies the unique id. If multiple remote debug services exist on one host, jstack -l 4089 >1. TXT // export the information to a file.Copy the code
-f If 'jstack [-l] pid' does not correspond to the stack information, it is used to force the Jstack if jstack does not respond directly. In general, the -l long list is not required. Printing additional information about locks, such as the Ownable Synchronizers list belonging to Java.util.Concurrent, will cause JVM pauses to be much longer (possibly many times worse, such as a few milliseconds in normal JStack and a single GC). -l is almost a second), and -L is not recommended. In general, you don't need to use -m to print all stack information for Java and native C/C ++ frameworks. Can print the JVM stack, display the Native stack frame, commonly used screening don't need to use - h | -help print information help pid need to be print configuration information of the Java process id, you can use the JPS queries.Copy the code
It is better to write the name of the thread in the code to check the thread information.
8.3 View all information using the code
import java.util.Map; public class AllStackTraces { public static void main(String[] args) { for (Map.Entry<Thread, StackTraceElement[]> stackTrace : Thread.getAllStackTraces().entrySet()) { Thread thread = (Thread) stackTrace.getKey(); StackTraceElement[] stack = (StackTraceElement[]) stackTrace.getValue(); if (thread.equals(Thread.currentThread())) { continue; } system.out.println (" thread: "+ thread.getName()); for (StackTraceElement stackTraceElement : stack) { System.out.println(stackTraceElement); }}}} Print result: "D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ bin \ Java" - javaagent: D: \ ideaIU - 2017.3.1 win (1) \ lib \ idea_rt jar = 61728: D: \ ideaIU - 2017.3.1 win \ bin - Dfile. (1) encoding = utf-8 - the classpath "D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ charsets jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ deploy the jar. D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ ext \ access - bridge - 64. The jar. D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ ext \ cldrdata jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ ext \ DNSNS jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ ext \ jaccess jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ ext \ JFXRT jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ ext \ localedata jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ ext \ nashorn jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ ext \ sunec jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ ext \ sunjce_provider jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ ext \ sunmscapi jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ ext \ sunpkcs11 jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ ext \ zipfs jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ javaws jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ jce jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ JFR jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ JFXSWT jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ jsse jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ management - agent jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ plugin jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ resources jar; D: \ \ Program Files \ Java \ jdk1.8.0 _92 \ jre \ lib \ rt jar; D:\Users\bobshute\IdeaProjects\out\production\jvmStu" AllStackTraces: Monitor Ctrl-Break java.net.SocketInputStream.socketRead0(Native Method) java.net.SocketInputStream.socketRead(SocketInputStream.java:116) java.net.SocketInputStream.read(SocketInputStream.java:170) java.net.SocketInputStream.read(SocketInputStream.java:141) sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284) sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326) sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178) java.io.InputStreamReader.read(InputStreamReader.java:184) java.io.BufferedReader.fill(BufferedReader.java:161) java.io.BufferedReader.readLine(BufferedReader.java:324) java.io.BufferedReader.readLine(BufferedReader.java:389) Com. Intellij. Rt. Execution. Application. AppMainV2 $1. The run (AppMainV2. Java: 64) threads: Attach the Listener threads: Signal Dispatcher thread: Finalizer java.lang.Object.wait(Native Method) java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143) java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164) Java. Lang. Ref. $FinalizerThread finalizers. Run (finalizers. Java: 209) threads: Reference Handler java.lang.Object.wait(Native Method) java.lang.Object.wait(Object.java:502) java.lang.ref.Reference.tryHandlePending(Reference.java:191) java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153) Process finished with exit code 0Copy the code
8.4 Operation Example
1. Top Finds the process that consumes the most CPU resources. Run the top command, default is the process view, Where PID is the process ID CO_ad2 18 0 1817m 776m 9712s 3.3 4.9 12:03.24 Java CO_ad 21 0 3028m 2.5G 9432s 1.0 16.3 6629:44 JA Top: shift+h or "h", shift+h or "h", then open the thread view. Pid indicates the thread ID. Co_ad2 15 0 1807m 630m 9492 S 1.3 4.0 0:05.12 Java CO_AD2_S 15 0 1360m 560m 9176 S 0.3 3.6 0:46.72 Java Here we examine the thread 21233, and note that this thread belongs to the process 21125. 3. Run the jstack command to output the current thread stack and save it in a file named jstack.log. Note: Output thread stack and save top command snapshot should be done at the same time. Because the jstack.log file records the thread ID in hexadecimal, you need to convert the thread ID displayed in the top command to hexadecimal. 4. Jstack to find this thread information jstack [process] | grep - A 10 [thread hexadecimal] : jstack 21125 | grep - A 10 52 f1 - A 10 said the same to find after 10 lines. 21233 is converted to hexadecimal 52F1 using a calculator. Note that the letters are lower case. Results: "http-8081-11" daemon prio=10 tid=0x00002aab049a1800 nid=0x52bb in Object.wait() [0x0000000042c75000] java.lang.Thread.State: WAITING (on object monitor) at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:485) at Org.apache.tomcat.util.net.JIoEndpoint$Worker.await JIoEndpoint. Java: (416) in the results for 52 f1, the current thread can be seen in what to do.Copy the code
8.4 Reference Articles
Java command – jStack tool
9 Visualization VM tool -Jconsole
9.1 introduction
JConsole has been introduced since Java 5. JConsole is a built-in Java performance analyzer that can be run from the command line or in a GUI shell. You can easily use JConsole (or its higher-end cousin, VisualVM) to monitor Java application performance and track code in Java.
If you have security concerns, you need authentication, you need a secure connection, that can be done. Reference: download.oracle.com/javase/6/do…
9.1 Jconsole Memory Monitoring
After the jConsole option is enabled in the bin directory, select a thread to view the memory status.
CMD -> jConsole -> Select threadCopy the code
9.2 Jconsole Thread Monitoring
package jconsole; import sun.applet.Main; import java.util.Scanner; public class TestJconsole { public static void main(String[] args) { Scanner sc = new Scanner(System.in); sc.next(); // Console input testWhileTrue(); sc.next(); // Enter testWait(new Object()) again; Private static void testWhileTrue() {new Thread(new Runnable() {@override public void run() {// CPU While (true){}}},"while true").start(); } private static void testWait(Object obj) {new Thread(new Runnable() {@override public void run() { synchronized (obj){ try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } },"wait").start(); Name: main status: RUNNABLE Total block count: 0, Total wait count: 0 Stack trace: java.io.FileInputStream.readBytes(Native Method) java.io.FileInputStream.read(FileInputStream.java:255) java.io.BufferedInputStream.read1(BufferedInputStream.java:284) Java. IO. BufferedInputStream. Read (BufferedInputStream. Java: 345) - has targeted the Java. IO. Ba590 BufferedInputStream @ 429 sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284) sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326) Sun. Nio. Cs. StreamDecoder. Read (StreamDecoder. Java: 178) - has targeted the Java. IO. InputStreamReader @ bd5bea1 java.io.InputStreamReader.read(InputStreamReader.java:184) java.io.Reader.read(Reader.java:100) java.util.Scanner.readInput(Scanner.java:804) java.util.Scanner.next(Scanner.java:1369) jconsole.TestJconsole.main(TestJconsole.java:11) 2. Name: While True Status: RUNNABLE Total blocks: 0, Total waits: 0 Stack trace: jconsole.TestJconsole$2.run(TestJconsole.java:41) java.lang.Thread.run(Thread.java:745) 3. Wait status: WAITING on java.lang.Object@31ca3217 Stack trace: 0, 1 java.lang.Object.wait(Native Method) java.lang.Object.wait(Object.java:502) jconsole.TestJconsole$1.run(TestJconsole.java:28) java.lang.Thread.run(Thread.java:745) */ }Copy the code
9.3 Jconsole Thread Deadlock Monitoring
Resources 1,2, threads A,B; A is going to lock 1 with 1 and then use 2,B is going to lock 2 with 2 and then use 1, and then do both, neither release, both wait. Cause a deadlock.
package jconsole.deatlock; public class DeadLock implements Runnable { private Object obj1; private Object obj2; public DeadLock(Object obj1,Object obj2){ this.obj1 = obj1; this.obj2 = obj2; } @Override public void run() { synchronized (obj1){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (obj2){ System.out.println("run core"); } } } } package jconsole.deatlock; public class TestDeadLock { public static void main(String[] args) { Object obj1 = new Object(); Object obj2 = new Object(); new Thread(new DeadLock(obj1,obj2),"thread1").start(); new Thread(new DeadLock(obj2,obj1),"thread1").start(); } /** You can view the following threads through jConsole: Name: Thread0 BLOCKED: java.lang.Object@50649ae7 Status: BLOCKED, owner: Thread-1 Total BLOCKED: 1, Total wait: 1 Stack trace: Jconsole. Deatlock. DeadLock. The run (DeadLock. Java: 22) - has targeted the Java. Lang. Object @ 5 e76a81d Java. Lang. Thread. The run (745) Thread. Java: Name: Thread-1 Status: BLOCKED on java.lang.Object@5e76a81d, Owner: Thread-0 Total blocks: 1, Total waits: 1 Stack trace: Jconsole. Deatlock. DeadLock. The run (DeadLock. Java: 22) - has targeted the Java. Lang. Object @ 50649 ae7 Java. Lang. Thread. The run (745) Thread. Java: * /}Copy the code
9.4 Introduction
9.4.1 StartPage
Overview: Displays Overview information about the Java VM and Monitored values. Memory: displays memory usage information Thread: displays thread usage information Class: displays class loading information VM Summary: displays Java VM information MBeans: displays MBeans
9.4.2 memory
It is useful to look at heap memory, non-heap memory, the state of the memory pool, overall memory allocation and usage, and how often and how long the different GC does garbage collection. You can manually perform GC to see memory changes.
GC algorithms and parameters can have a significant impact on performance. Pay attention to the number of GC times, times, partial GC and full GC, adjust the parameters for the different GC and GC you use, and then observe it in this view to get good performance.
9.4.3 thread
All active threads are displayed in the lower left corner (if there are too many threads, you can filter out the threads you want to observe by typing a string in the filter bar below). Clicking on a display shows the thread’s name, status, number of blocks and waits, and stack information.
The graph shows the peak number of threads (red) and currently active threads (blue).
There is also a button below “deadlock detected”.
9.4.4 class
9.4.5 VM profile
9.4.6 an
10. VisualVM usage details
VisualVM homepage
VisualVM plug-in address
You can also install plug-ins.
11. The JVM tuning
11.1 an overview of the
- knowledge
- tool
- data
- experience
11.2 Case 1- Large object
Cause: when each user logs in, a large object is generated, and the large object is directly assigned to the old age. There are too many objects logged in, causing not enough old ages, causing fullGC(because minorGC can’t solve the problem), and then causing fullGC to take too long due to large heap memory.
Memory allocation strategy:
- Eden is assigned priority
- Large objects are allocated directly to the old age
- Long-lived objects are assigned to the old age
- Space allocation guarantee
When space is scarce, borrow space from the old age
- Dynamic object age determination
Solution: a disassembly into multiple sets, each to reduce the memory (not good enough).
11.3 Case 2- Insufficient physical Memory (non-JVM)
Symptom: The memory overflows periodically. The memory size does not help. The heap snapshot information is exported without any information. The memory monitoring is normal.
Cause: To improve performance, NIO applies for off-heap memory, which needs to occupy the physical memory of the machine other than the VIRTUAL machine.
Note: Other cases where physical memory is not required by the JVM, such as meta-space.
12 and a half to summarize
- Principle + Tool + case
- The runtime area of the Java virtual machine
-
- Thread-exclusive stack, program counter, local method stack
-
- Thread shared area heap, method area
- Object creation and collection
-
- Algorithm for marking garbage objects
-
-
- Reference counting method
-
-
-
- Accessibility analysis
-
Garbage collection algorithms
-
-
- Mark-clear algorithm
Slowly,
-
-
-
- Replication algorithm
The new generation
-
-
-
- Tag sorting algorithm
The old s
-
-
-
- Generational collection algorithm
-
-
- Garbage collector Serial ParNew Parallel CMS G1
-
Object memory allocation principle
-
- Objects are first allocated in Eden
-
- Big object goes straight to the old age
-
- Long-lived objects enter the old age
-
- Space allocation guarantee
-
- Escape analysis and on-stack allocation
-
tool
-
- Command line tool JPS jstat jinfo jmap jhat jstart
-
- Graphical chemical tool jConsole VisualVM