JVM Monitoring and Diagnostics tools (command line)
The JDK command line
View JDK related command source code
JPS: View the Running Java process
View running Java processes
Java Process Status (JPS) displays all HotSpot VIRTUAL machine processes in a specified system. You can query the running virtual machine processes.
Note: For a local VM process, the local VM ID of the process is unique and the same as the PROCESS ID of the OPERATING system.
- JPS [options] [hostid]
- -q: Only LVMID (Local Virtual Machine ID) is displayed. Do not display the name of the main class, etc
- -1: prints the full class name of the application’s main class or the full jar path if the process executes a JAR package
- -m: Outputs the parameters passed to the main() class when the vm process starts
- -v: lists THE JVM parameters for starting vm processes. For example, -xMS20m -XMx50m is the JVM parameter specified by the startup program.
- Note: The above parameters can be used comprehensively.
- Supplement:
- If a Java process turns off the default UsePerfData parameter (using the -xx: -useperfData parameter), the JPS command (and the jstat described below) will not detect the Java process.
Hostid is the host name registered in the RMI registry.
If you want to remotely monitor Java programs on your host, you need to install JStatd. For network venues with more stringent security practices, it is possible to use a custom policy file to display access to a specific trusted host or network, although this technique is vulnerable to IP address fraud attacks.
If security issues cannot be handled using a custom policy file, the safest course of action is not to run the JStatd server, but to use the Jstat and JPS tools locally.
Jstat: View JVM statistics
Jstat (VM Statistics Monitoring Tool): a command line Tool used to monitor VM running status information. It can display classloading, memory, garbage collection, JIT compilation, and other running data in local or remote virtual machine processes.
The official documentation
The option can be composed of the following values.
- Class loading related:
- -class: displays ClassLoader information, such as the loading and unloading quantity of classes, total space, and time consumed by class loading
- -t: displays a Timestamp column before it
- -h3: outputs the title every three times
- 9000: indicates the process ID
- 1000: output every 1000 mm
- 10: Output 10 times in total
- -class: displays ClassLoader information, such as the loading and unloading quantity of classes, total space, and time consumed by class loading
- Garbage collection related:
- -gc: displays heap information related to GC. Including Eden area, two Survivor areas, old age, permanent generation capacity, used space, GC time total and other information.
- -gcCapacity: displays the same content as -gc, but the output focuses on the maximum and minimum space used by each area of the Java heap.
- -gcutil: Displays basically the same content as -gc, but the output focuses on the percentage of the total space used.
- -gCCause: Has the same function as -gcutil, but outputs an additional cause of the last or currently occurring GC.
- – gcNew: displays the Gc status of the new generation
- -gcnewCapacity: displays the same content as -gcnew. The output focuses on the maximum and minimum space used
- -geold: displays the Gc status of the old age
- -gcoldCapacity: displays the same content as -gcold. The output focuses on the maximum and minimum space used
- – gcpermCapacity: displays the maximum and minimum capacity used by the permanent generation.
- JIT related:
- – Compiler: Displays the compiled methods and time used by the JIT compiler
- -printcompilation: Outputs methods that have been JIT compiled
- Self command related:
- -interval: specifies the interval for outputting statistics, in milliseconds. That is, query interval
- -count: indicates the total number of queries
- -t: The output information can be preceded by a Timestamp column to display the running time of the program. Unit: second
- -h: a table header can be output after the number of rows of periodic data output
- GC Details output items
- Cenozoic correlation
- S0C is the size of the first survivor area (in bytes)
- S1C is the size of the second survivor area (in bytes)
- S0U is the size used by the first survivor area (in bytes)
- S1U is the size used by the second survivor area (in bytes)
- EC is the size of Eden space (in bytes)
- EU is the used size of Eden space (bytes)
- Old age correlation
- OC is the size of the old age (bytes)
- OU is the size that was used in the old age ((bytes)
- Method area (meta space) correlation
- MC is the size of the method area
- MU is the used size of the method area
- CCSC is the size of the compressed class space
- CCSU is the size used to compress the class space
- other
- YGC is the number of young GC counts from the start of the application to the time of sampling
- YGCT is the time (in seconds) consumed by young GC from application startup to sampling time
- FGC is the number of full GC counts from the start of the application to the time of sampling
- FGCT is the time (in seconds) consumed by full GC from application startup to sampling time
- GCT is the total time from application startup to GC at sampling time
- Jstat -oom Early warning check
We can compare the Java process startup time with the total GC time (GCT column), or the time between the two measurements and the increment of the total GC time to get a percentage of the elapsed time. If the ratio is more than 20%, it indicates that the current heap pressure is high; If the ratio exceeds 90%, there is little free space in the heap and an OOM exception could be thrown at any time.
GCT time/(next Timestamp- last Timestamp)
- Jstat determines if there is a memory leak
- Step 1: In a long-running Java program, we can run the jstat command to get multiple rows of performance data in a row and take the minimum value of the OU column (that is, old memory used) in those rows.
- Step 2: We then repeat the above operation at long intervals to obtain the minimum of multiple ou values. If these values are trending up, it indicates that the Java program’s memory usage has been increasing in the past, which means that the number of objects that cannot be reclaimed is increasing, and therefore there is a high probability of a memory leak.
Jinfo: View and modify JVM configuration parameters in real time
Configuration Info (jinfo for Java) : displays vm Configuration parameters and can be used to adjust vm Configuration parameters.
In many cases, Java applications do not specify all Java virtual machine parameters. At this point, the developer may not know the default value of a specific Java virtual machine parameter. In this case, you might need to look up the document to get a default value for a parameter. This search process can be very difficult. But with the JInfo tool, developers can easily find the current values of Java virtual machine parameters.
The basic syntax is jinfo [options] pid
Jinfo-sysprops PID: Can view the parameters obtained by system.getProperties ()
Real-time view
- Jinfo-flags PID: Displays some parameters that have been assigned values
- Jinfo-flag Parameter PID: Displays the parameter values of a Java process
Real-time modification
Jinfo can not only view the actual value of a Java virtual machine parameter at run time, but can even modify some parameters at run time and make them take effect immediately.
However, not all parameters support dynamic change. Parameters that are marked Manageable can only be modified in real time. In fact, this modification ability is extremely limited.
Can view is marked as manageable parameters: Java – XX: + PrintFlagsFinal – version | grep manageable
- For Boolean type: jinfo-flag [+/-] Specific parameter PID
- For non-boolean types: jinfo-flag Parameter = parameter value PID
- Java -xx :+PrintFlagsInitial: Views the initial values for all JVM parameters to start
- Java -xx :+PrintFlagsFinal: Displays the final values of all JVM arguments, with colons as modified values
- Java -xx :+PrintCommandLineFlags: Views the names and values of detailed XX parameters that have been set by the user or JVM
Jmap: Export memory image files & memory usage
Jmap (JVM Memory Map): On the one hand, it can get dump file (heap dump snapshot file, binary file), it can also get the target Java process Memory information, including the usage of various areas of the Java heap, heap object statistics, class loading information, etc. Official Help document
The basic syntax is:
- jmap [option] <pid>
- jmap [option] <executable <core>
- jmap [option] [server_id@] <remote server IP or hostname>
-dump
: Generates Java heap dump snapshot: dump file- Special: -dump:live saves only live objects in the heap
-heap
: Displays detailed information about the entire heap space, including GC usage, heap configuration, and memory usage-histo
: Outputs statistics about objects in the heap, including classes, number of instances, and total capacity- Special :-histo:live Counts only the live objects in the heap
- -permstat: displays permanent generation memory status information based on ClassLoader
- This parameter is valid only on Linux or Solaris
- – finalizerInfo: displays objects in the F-queue that are waiting for the Finalizer thread to execute the Finalize method
- This parameter is valid only on Linux or Solaris
- -f: If the VM process does not respond to the -dump option, you can use this option to forcibly generate the dump file
- This parameter is valid only on Linux or Solaris
- – h | -help: jmap tool using the help command
- -j
: Passes parameters to jMAP-started JVMS
Export the heap dump snapshot file
Export all living objects in the heap to a file. Heap Dump, also known as a Heap storage file, is a snapshot of the memory of a Java process at a certain point in time.
Full Gc is usually triggered before a Heap Dump file is written, so the Heap Dump file stores all the object information left after Ful1GC.
It takes a long time to generate dump files, especially for large-memory images.
- Manual mode
- Jmap-dump :format=b,file=
Jmap-dump :live,format=b,file=<filename.hprof> <pid>
- Jmap-dump :format=b,file=
Since JMap will access all objects in the heap, in order to ensure that it is not disturbed by application threads in the process, JMap needs to use a safety point mechanism that allows all threads to stay in state without changing the data in the heap. That is, the heap snapshot exported by JMap must be at a safe point location. This can lead to biased results based on the heap snapshot.
For example, if some objects in the compile-generated machine code have a lifetime between two safety points, the: live option will not be able to detect those objects.
In addition, if a thread fails to reach a safe point for a long time, JMap will wait forever. Unlike jstat, where the garbage collector actively stores the summary data required by Jstat in a fixed location, Jstat simply reads it.
- Automatic mode
-XX:+HeapDumpOnoutOfMemoryError
(Export the current heap snapshot of the application when the application occurs OOM.)-XX:HeapDumpPath=<filename.hprof>
(You can specify where to save the heap snapshot)
When the program exits OOM, some instantaneous information disappears with the termination of the program, and it is often difficult or time-consuming to reproduce OOM problems. If the dump file can be automatically exported in OOM, it is very urgent. Such as: – Xmx100m – XX: XX: + HeapDumpOnOutOfMemoryError – HeapDumpPath = D: \ m.h
Displays heap memory information
Jmap-heap PID: displays the memory usage of each area
Jmap-histo PID: Sort to view the sizes of various objects in the heap
Jhat: The JDK comes with a heap analysis tool
Jhat (JVM Heap Analysis Tool): The Jhat (JVM Heap Analysis Tool) command provided by the Sun JDK is used together with the jmap command to analyze Heap dump files (Heap dump snapshots) generated by jmap.
Jhat has a built-in HTTP/HTML server. After dump file analysis results are generated, users can view the analysis results (vm dump snapshot information) in the browser.
Using the jhat command, you start an HTTP service with port 7000, or http://localhost:7000/, which can be analyzed in the browser.
The jhat command has been removed from JDK9 and JDK10. It is recommended to use VisualVM instead.
Jstack: Prints snapshots of JVM threads
Function of generating thread snapshot: It can be used to locate the cause of a long pause in a thread, such as deadlock between threads, dead loop, and long wait caused by requesting external resources. These are common causes of thread pauses for long periods of time. When a thread pauses, jStack displays the stack of calls made by individual threads.
Official Help document
There are several states to look out for in Thread dump
Deadlock Deadlock
Waiting on condition
Waiting on monitor entry
Jam, Blocked
- Running, Runnable
- Suspended, Suspended
- In Object wait, object.wait () or TIMED_WAITING
- Stop, the Parked
The option parameter:
- -f: Forces the thread stack to be outputted when a normally outputted request is not answered
- -m: Displays additional information about the lock in addition to the stack
- -h: Displays the C/C++ stack if a local method is called
=/ * * *@DescriptionDeadlock example: jstack view deadlock *@Author: jianweil
* @date: 2021/9/6 16:07 * /
=public class DealLockTest {
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
new Thread(new Runnable() {
@Override
public void run(a) {
synchronized (o1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 is running");
synchronized (o2) {
System.out.println("Thread 2 gets O1"); }}}},Thread 1 "").start();
new Thread(new Runnable() {
@Override
public void run(a) {
synchronized (o2) {
System.out.println("Thread 2 is running");
synchronized (o1) {
System.out.println("Thread 2 gets O1"); }}}},Thread 2 "").start();
System.out.println("Main thread terminated"); }}Copy the code
Java gets stack information
Map<Thread, StackTraceElement[]> all = Thread.getAllStackTraces();// Trace all threads in the current process
Set<Map.Entry<Thread, StackTraceElement[]>> entries = all.entrySet();
for (Map.Entry<Thread, StackTraceElement[]> en : entries) {
Thread t = en.getKey();
StackTraceElement[] v = en.getValue();
System.out.println("【Thread name is :" + t.getName() + "】");
for (StackTraceElement s : v) {
System.out.println("\t"+ s.toString()); }}Copy the code
Output result:
【Thread name is :Finalizer】 Java.lang.object. Wait (Native Method) java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:144)
java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:165)
java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:216Java.lang.ClassLoader$NativeLibrary. Load (Native Method) java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1941)
java.lang.ClassLoader.loadLibrary(ClassLoader.java:1845)
java.lang.Runtime.loadLibrary0(Runtime.java:870)
java.lang.System.loadLibrary(System.java:1122)
java.net.InetAddress$1.run(InetAddress.java:295)
java.net.InetAddress$1.run(InetAddress.java:293)
java.security.AccessController.doPrivileged(Native Method)
java.net.InetAddress.<clinit>(InetAddress.java:292)
java.net.InetSocketAddress.<init>(InetSocketAddress.java:220)
java.net.Socket.<init>(Socket.java:211)
com.intellij.rt.execution.application.AppMainV2$1.run(AppMainV2.java:44Java.lang.object. Wait (Native Method) 【Thread name is :Reference Handler】 Java.lang.object. java.lang.Object.wait(Object.java:502)
java.lang.ref.Reference.tryHandlePending(Reference.java:191)
java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153) Java Thread name is: the main 】 【. Lang. Thread. DumpThreads (Native Method) Java. Lang. Thread. GetAllStackTraces (Thread. Java:1610)
com.atguigu.java.DealLockTest.main(DealLockTest.java:15)
【Thread name is :Attach Listener】
Copy the code
JCMD: multi-function command line
Since JDK 1.7, a command line tool, JCMD, has been added.
It is a versatile tool that can be used to do all of the previous commands except jstat. For example, use it to export heap, memory usage, view Java processes, export thread information, perform GC, JVM runtime, and so on. Official Help document
JCMD has most of the functions of Jmap, and it is recommended to use the JCMD command instead of the jmap command on the Oracle website
- Jcmd-l: Lists all JVM processes, equivalent to JPS -l
- JCMD PID help: Lists all supported commands for the specified process
- JCMD PID Command: displays the command data of a specified process
Pid help JCMD pid help JCMD pid help JCMD pid help JCMD pid help JCMD pid help JCMD pid help
Jstatd: remote host information collection
While the previous instructions dealt only with monitoring native Java applications, some of these monitoring tools also support monitoring of remote machines (e.g., JPS, JSTAT). To enable remote monitoring, use the JStatd tool.
The jstatd command is an RMI server program that acts as a proxy server to establish communication between the local computer and remote monitoring tools. The JStatd server passes native Java application information to the remote machine.
VisualVM monitors JAVA applications on remote hosts
In-depth understanding of the JVM family
- 1. In-depth understanding of the JVM (I) – Introduction and architecture
- 2. In-depth understanding of the JVM II – 1 classloader subsystem
- 3. In-depth understanding of THE JVM (III) – Runtime data area (virtual machine stack)
- 4. In-depth understanding of THE JVM (IV) – runtime data area (program counter + local method stack)
- 5. In-depth understanding of THE JVM (V) – Runtime data area (heap)
- 6. In-depth understanding of THE JVM (VI) – Runtime data area (methods area)
- 7. In-depth understanding of the JVM (vii) – execution engine (interpreter and JIT compiler)
- 8. An in-depth understanding of the JVM (8) – string constant pool
- 9. In-depth understanding of JVM (IX) – object instantiation and memory layout
- 10. In-depth understanding of JVM (x -) – bytecode level profiler execution
- 11. In-depth understanding of concepts related to JVM (xi) garbage collection
- 12. In-depth understanding of JVM (xii) – garbage collection algorithms
- 13. Take a closer look at the JVM (13) – garbage collector
- 14. Dig deep into the JVM (XIV) one – object distribution map
- 15. In-depth understanding of the JVM (XV) -class file structure
- 16. An in-depth understanding of the JVM (XVI) one bytecode instruction set
- 17. In-depth understanding of the JVM (17) -class lifecycle details
- 18. Further understanding of the JVM (18) — more about class loaders