JVM common tuning commands

preface:
Using the commands provided by the jvm can easily monitor the production and print the log information of the stack to help us locate the problem! Although there are many mature tools for jvm tuning: jconsole, the famous VisualVM, IBM's Memory Analyzer, etc., the Sun JDK monitoring and fault handling commands include jps jstat jmap jhat jstack jinfo, which will be introduced one by one below

jps

JVM Process Status Tool, which displays all HotSpot virtual machine processes in the specified system.

Command format

jps [options] [hostid]

option parameter

  • -l: output the full name of the main class or jar path
  • -q: output only LVMID
  • -m: output the parameters passed to main() when the JVM starts
  • -v: the specified JVM parameters are displayed when the output JVM starts

The [option] and [hostid] parameters can also be left blank.

Example:

$ jps -l -m
28920 org.apache.catalina.startup.Bootstrap start
11589 org.apache.catalina.startup.Bootstrap start
25816 sun.tools.jps.Jps -l -m

jstat

jstat(JVM statistics Monitoring) is a command used to monitor the running state information of the virtual machine. It can display the running data such as class loading, memory, garbage collection and JIT compilation in the virtual machine process.

Command format

jstat [option] LVMID [interval] [count]

parameter

  • [option]: operation parameters
  • LVMID: local virtual machine process ID
  • [interval]: time interval of continuous output
  • [count]: number of consecutive outputs

Overview of option parameters:

OptionDisplays
classBehavior statistics of class loader. Statistics on the behavior of the class loader.
compilerHotspot JIT compiler behavior statistics. Statistics of the behavior of the HotSpot Just-in-Time compiler.
gcBehavior statistics of garbage collection heap. Statistics of the behavior of the garbage collected heap.
gccapacityThe capacity of each garbage collection generation (young,old,perm) and their corresponding spatial statistics. Statistics of the capacities of the generations and their corresponding spaces.
gcutilOverview of garbage collection statistics. Summary of garbage collection statistics.
gccauseOverview of garbage collection statistics (the same as -gcutil), with reasons for the last two garbage collection events attached. Summary of garbage collection statistics (same as -gcutil), with the cause of the last and
gcnewNew generation behavior statistics. Statistics of the behavior of the new generation.
gcnewcapacityStatistics of Cenozoic and its corresponding memory space. Statistics of the sizes of the new generations and its corresponding spaces.
gcoldBehavioral statistics of the elderly and immortals. Statistics of the behavior of the old and permanent generations.
gcoldcapacityBehavioral statistics of the elderly. Statistics of the sizes of the old generation.
gcpermcapacityImmortality behavior statistics. Statistics of the sizes of the permanent generation.
printcompilationHotspot compilation method statistics. HotSpot compilation method statistics.

Detailed explanation of option parameter
-class
Monitor class loading, unloading quantity, total space and time spent

$ jstat -class 11589
 Loaded  Bytes  Unloaded  Bytes     Time   
 7035  14506.3     0     0.0       3.67
  • Loaded: the number of class es loaded
  • Bytes: class byte size
  • Unloaded: the number of class es not loaded
  • Bytes: the byte size of the unloaded class
  • Time: load time

-compiler
Output the number of JIT compiled methods, time-consuming, etc

$ jstat -compiler 1262
Compiled Failed Invalid   Time   FailedType FailedMethod
2573      1       0    47.60          1 org/apache/catalina/loader/WebappClassLoader findResourceInternal  
  • Compiled: compiled quantity
  • Failed: number of compilation failures
  • Invalid: invalid quantity
  • Time: compilation time
  • FailedType: failure type
  • FailedMethod: the fully qualified name of the failed method

-gc
Garbage collection heap behavior statistics, common commands

$ jstat -gc 1262
 S0C    S1C     S0U     S1U   EC       EU        OC         OU        PC       PU         YGC    YGCT    FGC    FGCT     GCT   
26112.0 24064.0 6562.5  0.0   564224.0 76274.5   434176.0   388518.3  524288.0 42724.7    320    6.417   1      0.398    6.815

C is the total Capacity, and U is the Capacity Used

  • S0c: total capacity of survivor0 area

  • S1C: total capacity of survivor1 area

  • S0u: used capacity of survivor0 area

  • S1u: used capacity of survivor1 area

  • EC: total capacity of Eden District

  • EU: capacity used in Eden area

  • OC: total capacity of old area

  • Ou: used capacity of old area

  • Current perm capacity of PC (KB)

  • Use of PU perm (KB)

  • YGC: new generation garbage collection times

  • YGCT: new generation garbage collection time

  • FGC: garbage collection times in old age

  • FGCT: garbage collection time in old age

  • GCT: total waste collection time

     $ jstat -gc 1262 2000 20
    

This command means that 1262 gc cases are output every 2000ms, a total of 20 times

-gccapacity
The same as - gc, but it also outputs the maximum and minimum space used by each region of the Java heap

$ jstat -gccapacity 1262
 NGCMN    NGCMX     NGC    S0C   S1C       EC         OGCMN      OGCMX      OGC        OC       PGCMN    PGCMX     PGC      PC         YGC    FGC 
614400.0 614400.0 614400.0 26112.0 24064.0 564224.0   434176.0   434176.0   434176.0   434176.0 524288.0 1048576.0 524288.0 524288.0    320     1  
  • NGCMN: minimum space occupied by Cenozoic
  • NGCMX: the largest space occupied by Cenozoic
  • OGCMN: the smallest space occupied by the old age
  • OGCMX: the largest space occupied by the old age
  • OGC: capacity of the current generation (KB)
  • OC: space of current generation (KB)
  • Pgcmn: minimum space occupied by perm
  • Pgcmx: maximum space occupied by perm

-gcutil
Same as - gc, but the output is the percentage of used space in the total space

$ jstat -gcutil 28920
S0     S1     E      O      P     YGC     YGCT    FGC    FGCT     GCT   
12.45   0.00  33.85   0.00   4.44  4       0.242     0    0.000    0.242

-gccause
Overview of garbage collection statistics (the same as -gcutil), with reasons for the last two garbage collection events attached

$ jstat -gccause 28920
S0     S1     E      O      P       YGC     YGCT    FGC    FGCT     GCT    LGCC                 GCC                 
12.45   0.00  33.85   0.00   4.44      4    0.242     0    0.000    0.242   Allocation Failure   No GC  
  • LGCC: recent reasons for garbage collection
  • GCC: reason for current garbage collection

-gcnew
Statistics on the behavior of the Cenozoic

$ jstat -gcnew 28920
S0C      S1C      S0U        S1U  TT  MTT  DSS      EC        EU         YGC     YGCT  
 419392.0 419392.0 52231.8    0.0  6   6    209696.0 3355520.0 1172246.0  4       0.242
  • TT: tenuring threshold
  • MTT: maximum tening threshold
  • DSS: survivor area size (KB)

-gcnewcapacity
Statistics of Cenozoic and its corresponding memory space

$ jstat -gcnewcapacity 28920
NGCMN      NGCMX       NGC      S0CMX     S0C     S1CMX     S1C       ECMX        EC        YGC   FGC 
 4194304.0  4194304.0  4194304.0 419392.0 419392.0 419392.0 419392.0  3355520.0  3355520.0     4     0
  • NGC: capacity of current young generation (KB)
  • S0CMX: maximum S0 space (KB)
  • S0C: current S0 space (KB)
  • ECMX: maximum eden space (KB)
  • EC: current eden space (KB)

-gcold
Statistics on the behavior of the old generation

$ jstat -gcold 28920
PC       PU        OC           OU       YGC    FGC    FGCT     GCT   
1048576.0  46561.7   6291456.0     0.0      4      0      0.000    0.242

-gcoldcapacity
Count the size and space of the old generation

$ jstat -gcoldcapacity 28920
 OGCMN       OGCMX        OGC         OC         YGC   FGC    FGCT     GCT   
6291456.0   6291456.0   6291456.0   6291456.0     4     0    0.000    0.242

-gcpermcapacity
Immortality behavior statistics

$ jstat -gcpermcapacity 28920
PGCMN      PGCMX       PGC         PC      YGC   FGC    FGCT     GCT   
1048576.0  2097152.0  1048576.0  1048576.0     4     0    0.000    0.242

-printcompilation
Statistics of hotspot compilation methods

$ jstat -printcompilation 28920
Compiled  Size  Type Method
1291      78     1    java/util/ArrayList indexOf
  • Compiled: the number of compilation tasks executed
  • Size: the number of bytes of the method bytecode
  • Type: compile type
  • Method: the class name and method name of the compiled method. The class name uses "/" instead of "." as the space separator. The method name is the method name of the given class. The format is consistent with the hotspot - XX: + printcompilation option

jmap

The jmap(JVM Memory Map) command is used to generate the heap dump file. If you do not use this command, you can also use the - XX:+HeapDumpOnOutOfMemoryError parameter to automatically generate the dump file when the virtual machine appears OOM. Jmap can not only generate dump files, but also query the details of finalize execution queue, Java heap and persistent generation, such as current utilization rate, which collector is currently used, etc.

Command format

jmap [option] LVMID

option parameter

  • Dump: generate heap dump snapshot
  • finalizerinfo: displays the objects in the F-Queue waiting for the finalizer thread to execute the finalizer method
  • Heap: displays Java heap details
  • histo: displays statistics of objects in the heap
  • permstat : to print permanent generation statistics
  • F: when - dump does not respond, the dump snapshot is forced to be generated

Example
-dump
Common formats

-dump::live,format=b,file=<filename> pid 

dump heap to file, format specifies the output format, live indicates that it is a living object, and file specifies the file name

$ jmap -dump:live,format=b,file=dump.hprof 28920
Dumping heap to /home/xxx/dump.hprof ...
 Heap dump file created

The suffix dump.hprof is used to open it directly with mat (memory analysis tool).

-finalizerinfo
Print information about objects waiting to be recycled

$ jmap -finalizerinfo 28920
Attaching to process ID 28920, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 24.71-b01
Number of objects pending for finalization: 0

You can see that there is no object waiting for the finalizer thread to execute the finalizer method in the current F-QUEUE queue.

-heap
Print the summary information of heap, the algorithm used by GC, the configuration of heap and the usage of wise heap, which can be used to judge the current memory usage and garbage collection

$ jmap -heap 28920
  Attaching to process ID 28920, please wait...
  Debugger attached successfully.
  Server compiler detected.
  JVM version is 24.71-b01  

  using thread-local object allocation.
  Parallel GC with 4 thread(s)//GC mode  

  Heap Configuration: //Heap memory initialization configuration
     MinHeapFreeRatio = 0 //Corresponding to the JVM startup parameter - XX:MinHeapFreeRatio, set the minimum idle ratio of JVM heap (default 40)
     MaxHeapFreeRatio = 100 //Corresponding to the JVM startup parameter - XX:MaxHeapFreeRatio, set the maximum idle ratio of JVM heap (default 70)
     MaxHeapSize      = 2082471936 (1986.0MB) //Corresponding JVM startup parameter - XX:MaxHeapSize = set the maximum size of JVM heap
     NewSize          = 1310720 (1.25MB)//Corresponding JVM startup parameter - XX:NewSize = set the default size of the 'new generation' of the JVM heap
     MaxNewSize       = 17592186044415 MB//Corresponding JVM startup parameter - XX:MaxNewSize = set the maximum size of the 'new generation' of the JVM heap
     OldSize          = 5439488 (5.1875MB)//Corresponding JVM startup parameter - XX: oldsize = < value >: sets the size of the 'old generation' of the JVM heap
     NewRatio         = 2 //Corresponding jvm startup parameter - XX:NewRatio =: 'new generation' and 'old generation' size ratio
     SurvivorRatio    = 8 //Corresponding jvm startup parameter - XX:SurvivorRatio = set the size ratio of Eden area and Survivor area in the young generation 
     PermSize         = 21757952 (20.75MB)  //Corresponding JVM startup parameter - XX: permsize = < value >: sets the initial size of the 'immortal generation' of the JVM heap
     MaxPermSize      = 85983232 (82.0MB)//Corresponding JVM startup parameter - XX: maxpermsize = < value >: sets the maximum size of the 'immortal generation' of the JVM heap
     G1HeapRegionSize = 0 (0.0MB)  

  Heap Usage://Heap memory usage
  PS Young Generation
  Eden Space://Eden memory distribution
     capacity = 33030144 (31.5MB)//Total capacity of Eden District
     used     = 1524040 (1.4534378051757812MB)  //Eden zone used
     free     = 31506104 (30.04656219482422MB)  //Remaining capacity of Eden area
     4.614088270399305% used //Utilization ratio of Eden District
  From Space:  //Memory distribution of one Survivor area
     capacity = 5242880 (5.0MB)
     used     = 0 (0.0MB)
     free     = 5242880 (5.0MB)
     0.0% used
  To Space:  //Memory distribution of another Survivor area
     capacity = 5242880 (5.0MB)
     used     = 0 (0.0MB)
     free     = 5242880 (5.0MB)
     0.0% used
  PS Old Generation //Current Old memory distribution
     capacity = 86507520 (82.5MB)
     used     = 0 (0.0MB)
     free     = 86507520 (82.5MB)
     0.0% used
  PS Perm Generation//Current immortal memory distribution
     capacity = 22020096 (21.0MB)
     used     = 2496528 (2.3808746337890625MB)
     free     = 19523568 (18.619125366210938MB)
     11.337498256138392% used  

  670 interned Strings occupying 43720 bytes.

You can clearly see the current situation of each region in the Java heap.

-histo
Print the object statistics of the heap, including the number of objects, memory size, etc. (because full gc will be performed before dump:live. If live is brought, only live objects will be counted. Therefore, the heap size without live is larger than that with live)

$ jmap -histo:live 28920 | more
 num     #instances         #bytes  class name
----------------------------------------------
   1:         83613       12012248  <constMethodKlass>
   2:         23868       11450280  [B
   3:         83613       10716064  <methodKlass>
   4:         76287       10412128  [C
   5:          8227        9021176  <constantPoolKlass>
   6:          8227        5830256  <instanceKlassKlass>
   7:          7031        5156480  <constantPoolCacheKlass>
   8:         73627        1767048  java.lang.String
   9:          2260        1348848  <methodDataKlass>
  10:          8856         849296  java.lang.Class
  ....

Only the first 10 lines were printed

xml class name is an object type. The description is as follows:

B  byte
C  char
D  double
F  float
I  int
J  long
Z  boolean
[  Array, such as[I express int[]
[L+Class name other objects

-permstat
Prints intelligent statistics of the classloader for the persistent storage area of Java heap memory. For each class loader, its name, activity, address, parent class loader, and the number and size of classes it loads are printed. In addition, the number and size of strings contained are also printed.

$ jmap -permstat 28920
  Attaching to process ID 28920, please wait...
  Debugger attached successfully.
  Server compiler detected.
  JVM version is 24.71-b01
  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>             3111    18154296          null          live    <internal>
  0x0000000600905cf8      1       1888    0x0000000600087f08      dead    sun/reflect/DelegatingClassLoader@0x00000007800500a0
  0x00000006008fcb48      1       1888    0x0000000600087f08      dead    sun/reflect/DelegatingClassLoader@0x00000007800500a0
  0x00000006016db798      0       0       0x00000006008d3fc0      dead    java/util/ResourceBundle$RBClassLoader@0x0000000780626ec0
  0x00000006008d6810      1       3056      null          dead    sun/reflect/DelegatingClassLoader@0x00000007800500a0

-F
Force mode. If the specified pid does not respond, use the jmap -dump or jmap -histo options. The live sub option is not supported in this mode.

jhat

The jhat(JVM Heap Analysis Tool) command is used in conjunction with jmap to analyze the dump generated by jmap. Jhat has built-in a micro HTTP/HTML server. After generating the dump analysis results, you can view them in the browser. It should be noted here that the analysis is generally not carried out directly on the server, because jhat is a time-consuming and hardware resource consuming process. Generally, the dump file generated by the server is copied to the local or other machine for analysis.

Command format

jhat [dumpfile]

parameter

  • -stack false|true turns off tracking object allocation call stack. If the allocation location information is not available in the heap dump, this flag must be set to false. The default value is true. >
  • -refs false|true turns off tracking of references to objects. The default value is true. By default, the returned pointer is an object pointing to other specific objects, such as backlinks or input references. All objects in the heap will be counted / calculated. >
  • -Port port number sets the port number of the jhat HTTP server. The default value is 7000. >
  • -A file that lists data members that should be excluded from the reachable objects query. For example, if java.lang.String.value is listed in the file column, when the reachable object list is o calculated from a specific object, the reference path involving java.lang.String.value will be excluded. >
  • -Baseline exclude file specifies a baseline heap dump. Objects with the same object ID in two heap dumps will be marked as not being new. Other objects will be marked as new. It is useful when comparing two different heap dumps. >
  • -debug int sets the debug level. 0 means no debug information is output. The higher the value, the more detailed debug information will be output. >
  • -After version is started, just display the version information and exit >
  • -J < flag > because the jhat command actually starts a JVM for execution, you can pass in some startup parameters when starting the JVM through - J. for example, - J-Xmx512m specifies that the maximum heap memory used by the Java virtual machine running jhat is 512 MB. If you need to use multiple JVM startup parameters, you can pass in multiple - Jxxxxxx

Example

$ jhat -J-Xmx512m dump.hprof
  eading from dump.hprof...
  Dump file created Fri Mar 11 17:13:42 CST 2016
  Snapshot read, resolving...
  Resolving 271678 objects...
  Chasing references, expect 54 dots......................................................
  Eliminating duplicate references......................................................
  Snapshot resolved.
  Started HTTP server on port 7000
  Server is ready.

The - J-Xmx512m in the middle is to allocate 512M memory to start the HTTP server when the dump snapshot is large. After running, you can open h in the browser ttp://localhost:7000 Snapshot analysis heap snapshot analysis is mainly performed in the last head histogram, which lists all surviving objects during dump according to class.

When analyzing the same dump snapshot, the additional memory required by MAT is much smaller than that of jhat, so it is recommended to use MAT for analysis. Of course, it also depends on personal preferences.

analysis
Open browser H ttp://localhost:7000 , this page provides several query functions:

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

Generally, you can view heap exceptions mainly in two parts: Show instance counts for all classes (excluding platform), and all object information outside the platform. As shown below:
Show heap histogram shows the heap in a tree view. As shown below:
Specific troubleshooting needs to be combined with the code to observe whether a large number of objects that should be recycled are always referenced or whether there are objects that occupy a large amount of memory that cannot be recycled.
Generally, it will go down to the client and use tools to analyze

jstack

Jstack is used to generate a thread snapshot of the Java virtual machine at the current time. Thread snapshot is a collection of method stacks being executed by each thread in the current Java virtual machine. The main purpose of generating thread snapshot is to locate the causes of long-time pause of threads, such as deadlock between threads, dead loop, long wait caused by requesting external resources, etc. When a thread pauses, you can view the call stack of each thread through jstack to know what the unresponsive thread is doing in the background or waiting for resources. If a java program crashes and generates a core file, the jstack tool can be used to obtain the information of the java stack and native stack of the core file, so that you can easily know how the Java program crashes and where the problem occurs in the program. In addition, the jstack tool can also be attached to the running Java program to see the information of the java stack and native stack of the running Java program at that time. Jstack is very useful if the running Java program presents a hung state.

Command format

jstack [option] LVMID

option parameter

  • -F: force the output thread stack when the normal output request is not responded
  • -l: displays additional information about locks in addition to the stack
  • -m: if you call a local method, you can display the C/C + + stack

Example

$ jstack -l 11494|more
2016-07-28 13:40:04
Full thread dump Java HotSpot(TM) 64-Bit Server VM (24.71-b01 mixed mode):

"Attach Listener" daemon prio=10 tid=0x00007febb0002000 nid=0x6b6f waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
        - None

"http-bio-8005-exec-2" daemon prio=10 tid=0x00007feb94028000 nid=0x7b8c waiting on condition [0x00007fea8f56e000]
   java.lang.Thread.State: WAITING (parking)
        at sun.misc.Unsafe.park(Native Method)
        - parking to wait for  <0x00000000cae09b80> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
        at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
        at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
        at org.apache.tomcat.util.threads.TaskQueue.take(TaskQueue.java:104)
        at org.apache.tomcat.util.threads.TaskQueue.take(TaskQueue.java:32)
        at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1068)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)

   Locked ownable synchronizers:
        - None
      .....

jinfo

jinfo(JVM Configuration info) is used to view and adjust the virtual machine running parameters in real time. The previous jps -v password can only view and display the specified parameters. If you want to view the values of the specified parameters that are not displayed, you need to use the jinfo password

Command format

jinfo [option] [args] LVMID

option parameter

  • -flag: outputs the value of the specified args parameter

  • -flags: the args parameter is not required, and the values of all JVM parameters are output

  • -sysprops: output system properties, equivalent to System.getProperties()
    Example

     $ jinfo -flag 11494
     -XX:CMSInitiatingOccupancyFraction=80
    

Tags: Java jvm

Posted on Mon, 13 Sep 2021 22:23:53 -0400 by itsjareds