Comprehensive analysis of high-level core knowledge in Java-JDK monitoring and troubleshooting tools (Detailed explanation of JDK command line tools!, JDK visual analysis tool usage!)

1. JDK command line tool

These commands are in the bin directory under the JDK installation directory:

  • jps(JVM Process Status): UNIX-like pscommands. The user views the startup class, incoming parameters and Java virtual machine parameters of all Java processes;
  • jstat (JVM Statistics Monitoring Tool): Used to collect all aspects of HotSpot virtual machine operating data;
  • jinfo (Configuration Info for Java): Configuration Info forJava, displays virtual machine configuration information;
  • jmap (Memory Map for Java): Generate heap dump snapshot;
  • jhat (JVM Heap Dump Browser): Used to analyze heapdump files, it will establish an HTTP/HTML server, allowing users to view the analysis results on the browser;
  • jstack (Stack Trace for Java): Generate a thread snapshot at the current moment of the virtual machine. The thread snapshot is the collection of method stacks being executed by each thread in the current virtual machine.

1.jps: View all Java processes

jps(JVM Process Status) command UNIX-like pscommands.

jps: Displays the name of the main class of virtual machine execution and the unique ID (Local Virtual Machine Identifier, LVMID) of these processes. jps -q: Only output the unique ID of the local virtual machine of the process.

C:\Users\SnailClimb>jps 
7360 NettyClient2 
17396 
7972 Launcher 
16504 Jps 
17340 NettyServer

jps -l : Output the full name of the main class. If the process is executing the Jar package, output the Jar path.

C:\Users\SnailClimb>jps -l 
7360 firstNettyDemo.NettyClient2 
17396 
7972 org.jetbrains.jps.cmdline.Launcher 
16492 sun.tools.jps.Jps 
17340 firstNettyDemo.NettyServer

jps -v : Output the JVM parameters when the virtual machine process starts.

jps -m : Output the parameters passed to the main() function of the Java process.

2.jstat: monitor various operating status information of virtual machines

jstat (JVM Statistics Monitoring Tool) A command line tool used to monitor various operating status information of virtual machines. It can display the class information, memory, garbage collection, JIT compilation and other running data of the virtual machine process locally or remotely (requires RMI support from the remote host). On a server that does not have a GUI and only provides a plain text console environment, it It will be the tool of choice for locating virtual machine performance problems during operation.

jstat Command format:

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

For example, jstat -gc -h3 31736 1000 10shows an analysis process with id 31736 gc case, the record is printed once every 1000ms, 10 times to stop printing, printing indicators head after every three lines.

Common options are as follows:

  • jstat -class vmid:Display related information of ClassLoader;
  • jstat -compiler vmid:Display related information of JIT compilation;
  • jstat -gc vmid: Display heap information related to GC;
  • jstat -gccapacity vmid: Display the capacity and usage of each generation;
  • jstat -gcnew vmid: Display new generation information;
  • jstat -gcnewcapcacity vmid:Display the size and usage of the new generation;
  • jstat -gcold vmid: Display the behavior statistics of the old generation and permanent generation. Starting from jdk1.8, this option only represents the old generation because the permanent generation has been removed;
  • jstat -gcoldcapacity vmid: Show the size of the old age;
  • jstat -gcpermcapacity vmid: Display the size of the permanent generation. Starting from jdk1.8, this option no longer exists because the permanent generation has been removed;
  • jstat -gcutil vmid: Display garbage collection information;

Further, with -tthe parameters listed may be added in a Timestamp information is output to display the running time of the program.

3.jinfo: View and adjust the parameters of the virtual machine in real time

jinfo vmid : Output all the parameters and system attributes of the current JVM process (the first part is the system attributes, and the second part is the JVM parameters).

jinfo -flag name vmid: Output the specific value of the parameter corresponding to the name. For example, output MaxHeapSize and check whether the current jvm process is enabled to print GC logs ( -XX:PrintGCDetails: detailed GC log mode, both of which are disabled by default).

C:\Users\SnailClimb>jinfo -flag MaxHeapSize 17340 
-XX:MaxHeapSize=2124414976 
C:\Users\SnailClimb>jinfo -flag PrintGC 17340 
-XX:-PrintGC

Using jinfo, you can dynamically modify the parameters of the jvm without restarting the virtual machine. Especially the online environment is particularly useful, please see the following example:

jinfo -flag [+|-]name vmidTurn on or off the parameter of the corresponding name.

C:\Users\SnailClimb>jinfo -flag PrintGC 17340 
-XX:-PrintGC 

C:\Users\SnailClimb>jinfo -flag +PrintGC 17340 

C:\Users\SnailClimb>jinfo -flag PrintGC 17340 
-XX:+PrintGC

4.jmap: Generate heap dump snapshot

jmapThe (Memory Map for Java) command is used to generate heap dump snapshots. If you don't use the jmap command, you can use the " -XX:+HeapDumpOnOutOfMemoryError" parameter to get the Java heap dump, which allows the virtual machine to automatically generate a dump file after the OOM exception occurs. Under Linux commands, you can kill -3also get the dump file by sending the process exit signal.

jmapThe role of is not just to get the dump file, it can also query the finalizer execution queue, Java heap and permanent generation details, such as space usage, which collector is currently used, etc. And jinfo, as jmapthere are many features in the Windows platform it is also restricted.

Example: Output a heap snapshot of a specified application to the desktop. Later, you can analyze the heap file with tools such as jhat and Visual VM.

C:\Users\SnailClimb>jmap - 
dump:format=b,file=C:\Users\SnailClimb\Desktop\heap.hprof 17340 
Dumping heap to C:\Users\SnailClimb\Desktop\heap.hprof ... 
Heap dump file created

5. jhat: Analyze the heapdump file

jhat Used to analyze the heapdump file, it will establish an HTTP/HTML server, allowing users to view the analysis results on the browser.

C:\Users\SnailClimb>jhat C:\Users\SnailClimb\Desktop\heap.hprof 
Reading from C:\Users\SnailClimb\Desktop\heap.hprof... 
Dump file created Sat May 04 12:30:31 CST 2019 
Snapshot read, resolving... 
Resolving 131419 objects... 
Chasing references, expect 26 dots.......................... 
Eliminating duplicate references.......................... 
Snapshot resolved. 
Started HTTP server on port 7000
 Server is ready.

Visit http://localhost:7000/

6.jstack: Generate a thread snapshot of the virtual machine at the current moment

jstackThe (Stack Trace for Java) command is used to generate a thread snapshot of the virtual machine at the current moment. The thread snapshot is the collection of method stacks being executed by each thread in the current virtual machine.

The purpose of generating a thread snapshot is mainly to locate the cause of a long pause in a thread, such as deadlock between threads, an infinite loop, and a long wait caused by requesting external resources, which are all causes of a long pause in a thread. When the thread through the pause jstackto view the call stack of each thread, you can know that is not responding thread in the end to do something in the background, waiting for something or resources.

Below is the code for a thread deadlock. Next, we will use the jstack command to perform deadlock check, output deadlock information, and find the thread where the deadlock occurs.

public class DeadLockDemo {
    
     
	private static Object resource1 = new Object();//资源 1 
	private static Object resource2 = new Object();//资源 2 
	
	public static void main(String[] args) {
    
     
		new Thread(() -> {
    
     
			synchronized (resource1) {
    
     
				System.out.println(Thread.currentThread() + "get resource1"); 
				try {
    
    
					Thread.sleep(1000); 
				} catch (InterruptedException e) {
    
     
					e.printStackTrace(); 
				}
				System.out.println(Thread.currentThread() + "waiting get resource2"); 
				synchronized (resource2) {
    
     
					System.out.println(Thread.currentThread() + "get resource2"); 
				} 
			} 
		}, "线程 1").start(); 
		
		new Thread(() -> {
    
     
			synchronized (resource2) {
    
     
				System.out.println(Thread.currentThread() + "get resource2"); 
				try {
    
    
					Thread.sleep(1000);
				} catch (InterruptedException e) {
    
     
					e.printStackTrace(); 
				}
				System.out.println(Thread.currentThread() + "waiting get resource1"); 
				synchronized (resource1) {
    
     
					System.out.println(Thread.currentThread() + "get resource1"); 
				} 
			} 
		}, "线程 2").start(); 
	} 
}

Output

Thread[线程 1,5,main]get resource1 
Thread[线程 2,5,main]get resource2 
Thread[线程 1,5,main]waiting get resource2 
Thread[线程 2,5,main]waiting get resource1

Thread A obtains the monitor lock of resource1 through synchronized (resource1), and then passes Thread.sleep(1000); let thread A sleep for 1s in order to allow thread B to be executed and then obtain the monitor lock of resource2. Thread A and Thread B both begin to request resources from each other after they have finished sleeping, and then the two threads will fall into a state of waiting for each other, which also produces a deadlock.

By jstackcommand analysis:

C:\Users\SnailClimb>jps 
13792 KotlinCompileDaemon 
7360 NettyClient2 
17396 
7972 Launcher 
8932 Launcher 
9256 DeadLockDemo 
10764 Jps 
17340 NettyServer 

C:\Users\SnailClimb>jstack 9256

Part of the output is as follows:

Found one Java-level deadlock: 
============================= 
"线程 2": 
	waiting to lock monitor 0x000000000333e668 (object 0x00000000d5efe1c0, a java.lang.Object), 
	which is held by "线程 1" 
"线程 1": 
	waiting to lock monitor 0x000000000333be88 (object 0x00000000d5efe1d0, a java.lang.Object), 
	which is held by "线程 2" 

Java stack information for the threads listed above: ===================================================
"线程 2":
	at DeadLockDemo.lambda$main$1(DeadLockDemo.java:31) 
	- waiting to lock <0x00000000d5efe1c0> (a java.lang.Object) 
	- locked <0x00000000d5efe1d0> (a java.lang.Object) 
	at DeadLockDemo$$Lambda$2/1078694789.run(Unknown Source) 
	at java.lang.Thread.run(Thread.java:748) "线程 1":
	at DeadLockDemo.lambda$main$0(DeadLockDemo.java:16) 
	- waiting to lock <0x00000000d5efe1d0> (a java.lang.Object) 
	- locked <0x00000000d5efe1c0> (a java.lang.Object) 
	at DeadLockDemo$$Lambda$1/1324119927.run(Unknown Source) 
	at java.lang.Thread.run(Thread.java:748) 

Found 1 deadlock.

You can see that the jstack command has helped us find specific information about the thread where the deadlock occurred.

Students who want to get this learning material can click [这里](https://jq.qq.com/?_wv=1027&k=2BS0mHEE) to get it

Two, JDK visual analysis tool

1.JConsole: Java monitoring and management console

JConsole is a visual monitoring and management tool based on JMX. Can easily monitor the memory usage of the java process of the local and remote servers. You can output in the console consolecommand to start or found in the bin directory under the JDK directory jconsole.exeand double-click to start.

Connecting to Jconsole

If you need to use JConsole to connect to a remote process, you can add the following parameters when the remote Java program starts:

-Djava.rmi.server.hostname=外网访问 ip 地址 
-Dcom.sun.management.jmxremote.port=60001 //监控的端口号 
-Dcom.sun.management.jmxremote.authenticate=false //关闭认证 
-Dcom.sun.management.jmxremote.ssl=false

When using JConsole to connect, the remote process address is as follows:

Internet access ip address: 60001

View Java program overview

memory monitoring

JConsole can display detailed information about the current memory. It not only includes the overall information of heap memory/non-heap memory, but also the usage of eden area and survivor area, as shown in the figure below.

Click the "Execute GC(G)" button on the right to force the application to execute a Full GC.

  • Cenozoic GC (Minor GC) : Refers to the garbage collection that occurs in the Cenozoic. Minor GC is very frequent and the recovery speed is generally faster.
  • Old GC (Major GC/Full GC) : Refers to the GC that occurred in the old age. Major GC is often accompanied by at least one Minor GC (not absolute). The speed of Major GC is generally more than 10 times slower than that of Minor GC. .

    Thread monitoring

Similarly we speak in front of jstackthe command, but this is visualization.

There is a "Detect Deadlock (D)" button at the bottom. Click this button to automatically find the thread that has the deadlock and their detailed information.

2.Visual VM: All-in-one troubleshooting tool

VisualVM provides detailed information of Java applications running on the Java Virtual Machine (JVM). In the graphical user interface of VisualVM, you can view related information about multiple Java applications conveniently and quickly.

The following paragraph is excerpted from "In-Depth Understanding of the Java Virtual Machine".

VisualVM (All-in-One Java Troubleshooting Tool) is the most powerful operation monitoring and fault handling program released with JDK so far. The official description of "All-in-One" is written in the software description of VisualVM The words indicate that besides running monitoring and troubleshooting, it also provides many other functions, such as profiling. The performance analysis function of VisualVM is not inferior to professional and paid profiling tools such as JProfiler and YourKit, and VisualVM also has a big advantage: it does not require the monitored program to run based on a special Agent, so it is very important to the application. The impact of the actual performance is very small, so that it can be directly applied in the production environment. This advantage is not comparable to tools such as JProfiler and YourKit.

VisualVM is developed based on the NetBeans platform, so it has the characteristics of plug-in extension functions from the beginning. Through plug-in extension support, VisualVM can do:

  • Display virtual machine processes and their configuration and environment information (jps, jinfo).
  • Monitor the application's CPU, GC, heap, method area, and thread information (jstat, jstack).
  • dump and analyze heap dump snapshots (jmap, jhat).
  • Method-level program performance analysis finds the method that is called the most and has the longest running time.
  • Offline program snapshot: Collect the program's runtime configuration, thread dump, memory dump and other information to create a snapshot, which can be sent to the developer for bug feedback.
  • Infinite possibilities of other plugins...

Reference materials: "Comprehensive Analysis of Java Intermediate and Advanced Core Knowledge"
Students who want to obtain this learning material can click here to get it

Guess you like

Origin blog.csdn.net/Java_Caiyo/article/details/111052637