Before we understand the virtual machine related technology, probably virtual machine has a more systematic understanding. Most of the above is theoretical knowledge, but some will be mixed with some practical operation, but the actual problem is far from enough, let’s use the JDK official gadget to practice. Accurate use of tools improves our efficiency in locating and solving problems.

1. JPS: tool for vm process status

The JPS (JVM Process Status Tool) is a Tool that lists the running PROCESSES of a VM. You can also specify the name of the Main Class that the VM executes and the unique Local Virtual Machine Identifier (LVMID) of these processes. This command is by far the most frequently used JDK command line tool (because most other JDK tools need to import LVMID to determine which VM process to monitor).

For local VM processes, LVMID is consistent with the Process ID (PID) of the OPERATING system (OS). You can also query LVMID using the Windows task manager or the UNIX ps command. However, if multiple VM processes are running at the same time, When you cannot locate by process name, you must rely on the JPS command to display the main class.

JPS command format

jps [ options ] [ hostid ]

Run JPS without any arguments as follows

ajisun@ajisun-2 /> jps
81746 Launcher
80005 
16153 Jps
555 Check
Copy the code

This output shows that there are currently four applications on the system, of which the third Jps is the command itself (which is also essentially a Java program).

Jps can also add parameters to control the output (-q, -m, -l, -v).

jps -q

Output only the process ID(LVMID), omitting the name of the main class

ajisun@ajisun-2 /> jps -q
51573
537
Copy the code

jps -m

Prints the arguments passed to the main() function of the main class when the virtual machine process starts

ajisun@ajisun-2 /> jps -m
51585 Jps -m
537 Check Point/Mobile Access/CShell.jar
Copy the code

jps -l

Print the full name of the main class and the jar path if the process executes a JAR package

ajisun@ajisun-2 /> jps -l
51639 sun.tools.jps.Jps
537 /Users/ajisun/Library/Check
Copy the code

jps -v

Output the JVM parameters when the virtual machine process starts

ajisun@ajisun-2 /> jps -v 51749 sun.tools.jps.Jps -l -m -v - Denv. Class. Path =. : / Library/Java/JavaVirtualMachines jdk1.8.0 _161. JDK/Contents/Home/lib/dt. The jar: / Library/Java/JavaVirtual Those/jdk1.8.0 _161. JDK/Contents/Home/lib/tools. The jar - Dapplication. Home = / Library/Java/JavaVirtualMachines jdk1.8.0 _161. JDK/Contents/home - Xms8m 537 /Users/ajisun/Library/Check Point/Mobile Access/CShell.jarCopy the code

2. Jinfo: Java configuration information tool

The Configuration Info for Java (JINFO) function allows you to view and adjust VM parameters in real time.

The basic grammar

jinfo [option] {pid}

Where option can be

  • -flag {name} Displays parameter values of a specified Java VM.
  • – flag [+ | -] {name} setting specifies the Java virtual machine parameters of Boolean value. (+ for true, – for false)
  • -flag {name}={value} Sets the parameters of a specified Java VM

For example, printing the age of the new generation advancing to the older generation

ajisun@ajisun-2 /> jinfo -flag MaxTenuringThreshold 11825
-XX:MaxTenuringThreshold=15
Copy the code

For example, whether to print GC information

ajisun@ajisun-2 /> jinfo -flag PrintGC 12046
-XX:-PrintGC
Copy the code

In addition to the lookup parameters above, set parameters are supported (not all parameters support this setting)

The parameters for manually opening GC logs can be turned on or off dynamically

ajisun@ajisun-2 /> jinfo-flag PrintGC 12190 // View the parameters are not set. -xx: -printgc ajisun@ajisun-2 /> jinfo-flag +PrintGC 12190 // Set parameters ajisun@ajisun-2 /> jinfo -flag PrintGC 12190 // Check that the parameters have been set -xx :+PrintGCCopy the code

3. Jmap: Java memory mapping tool

The jmap(Memory Map for Java) command is used to generate heapdump snapshots (commonly known as heapdump or dump files). Jmap is not just for taking heap dump snapshots. It can also query Finalize execution queues, Java heap, and method areas for details such as space utilization, which collector is currently in use, etc.

The basic grammar

jmap [option] {pid}

Where option can be

  • -dump: Generates a Snapshot of the Java heap dump. The format is: -dump:[live,]format=b,file={filename}. The live subparameter specifies whether to dump only live objects.
  • – Finalizerinfo: displays objects waiting for Finalizer thread to finalize finalize method in f-Queue. The finalizerinfo is valid only in Linux or Solaris.
  • -heap: displays heap details, such as the payback period, parameter Settings, and bandaging status. This parameter is available only on Linux or Solaris.
  • -histo: displays statistics about objects in the heap, including the number of classes, instances, and total capacity.
  • – clSTATS: displays the memory status of the permanent generation based on ClassLoader. It 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 a dump snapshot. This option is available only on Linux or Solaris.

Dump exports application snapshots

ajisun@ajisun-2 /> jmap -dump:format=b,file=/Users/ajisun/Desktop/jvmTest/s.txt 13157
Dumping heap to /Users/ajisun/Desktop/jvmTest/s.txt ...
Heap dump file created
Copy the code

You can analyze this snapshot using JHAT or another tool.

4. Jhat: Analyze the heap snapshot contents of Java applications

The jHAT (JVM Heap Analysis Tool) command is provided by the JDK and used in conjunction with Jmap to analyze Heap dump snapshots generated by Jmap.

As in dump file above

ajisun@ajisun-2 /> jhat /Users/ajisun/Desktop/jvmTest/s.txt
Reading from /Users/ajisun/Desktop/jvmTest/s.txt...
Dump file created Tue Jan 04 15:05:15 CST 2022
Snapshot read, resolving...
Resolving 19265 objects...
Chasing references, expect 3 dots...
Eliminating duplicate references...
Snapshot resolved.
Started HTTP server on port 7000
Server is ready.
Copy the code

The above output is analyzed and can also be viewed in a browser at http://localhost:7000

The information shown in the figure is a link to analyzing memory leaks using both “Show heap histogram,” which seeks out objects with the largest total capacity in memory, and “OQL,” a standard object query language. Query statistics on memory objects using sqL-like syntax (click on OQL Help in the image below to see the syntax)

Extra: JHAT is generally not used to analyze snapshots directly because it takes up a lot of server resources, and because it is relatively simple and better analysis tools are available, such as VisualVM.

5. Jstack: Java stack trace tool

The jstack(Stack Trace for Java) command is used to generate a snapshot (threaddump or Javacore file) of vm threads at the current time. Thread snapshot is the current virtual machine within each thread is executing method stack collection, generate thread snapshot is usually the purpose of locating the thread a long pause, such as deadlock between threads, infinite loop, request external resources lead to hang up for a long time and so on, are all lead to a common cause of thread long pause. By looking at the call stack of individual threads when a thread pauses, you can get a sense of what the unresponsive thread is doing in the background, or what resources it is waiting for.

The basic grammar

jstack [ option ] {pid}

Where option can be

  • -f: Forces the thread stack to be outputted when a normally outputted request is not answered.
  • -l: Displays information about locks except for stacks.

For example,

**ajisun@ajisun-2 /> jstack -l 12190** 2022-01-04 19:48:41 Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.161 - b12 mixed mode) : "Attach Listener" #11 daemon prio=9 os_prio=31 tid=0x00007f8f358db800 nid=0x3407 waiting on condition [0x0000000000000000] java.lang.Thread.State: RUNNABLE "Service Thread" #10 daemon prio=9 os_prio=31 tid=0x00007f8f360a8800 nid=0x4003 runnable [0x0000000000000000] java.lang.Thread.State: RUNNABLE .......Copy the code

Demonstrate while loop information viewing

public class Test {
    public static void main(String[] args) {
        while (true){
        }
    }
}
Copy the code
ajisun@ajisun-2 /> jps -l

24513 com.ajisun.coding.ajisunmybatis.Test

ajisun@ajisun-2 /> jstack -l 24513
Copy the code

In the figure above you can see the thread in the RUNNABLE state, in com. Ajisun. Coding. Ajisunmybatis. Test. The main method of 15 lines appear dead circulation. Threads such as dead loops, waits, deadlocks, etc., can be seen in specific locations.

The case of deadlock

Public class Test {private static Object objectA = new Object(); private static Object objectB = new Object(); Public static void main(String[] args) {new Thread(() -> {synchronized (objectA) {system.out.println (" obtain lock objectA"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (objectB) {system.out.println (" obtain lock objectB"); } } }).start(); New Thread(() -> {synchronized (objectB) {system.out.println (" obtain lock objectB"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (objectA) {system.out.println (" obtain lock objectA"); } } }).start(); }}Copy the code

To start with the jstack command, find the PID of the class through JPS

ajisun@ajisun-2 /> jps -l
25537 com.ajisun.coding.ajisunmybatis.Test
ajisun@ajisun-2 /> jstack -l 25537
Copy the code

As shown above, the location of the deadlock can be determined from the output information. And the two threads that deadlock hold objects for each other and for waiting objects.

Extra: JStack can not only get the stack information of the thread, but also see whether the thread is deadlocked and the details of the deadlock.

6. JCMD: multi-function command line

JCMD (Java Command) virtual machine diagnostic Command tool, a multifunctional Command, you can export heap, view Java process, export thread information, perform GC, etc., starting from jdk1.7.

View VMS in the system

ajisun@ajisun-2 /> jcmd -l
36372 com.ajisun.coding.ajisunmybatis.Allocation
36425 sun.tools.jcmd.JCmd -l
11423 
Copy the code

Query the commands supported by VM 36372

ajisun@ajisun-2 /> jcmd 36372 help
36372:
The following commands are available:
JFR.stop
JFR.start
JFR.dump
JFR.check
VM.native_memory
VM.check_commercial_features
VM.unlock_commercial_features
ManagementAgent.stop
ManagementAgent.start_local
ManagementAgent.start
GC.rotate_log
Thread.print
GC.class_stats
GC.class_histogram
GC.heap_dump
GC.run_finalization
GC.run
VM.uptime
VM.flags
VM.system_properties
VM.command_line
VM.version
help
Copy the code

The commands supported by this VIRTUAL machine are displayed above

  • View the vm startup time

    ajisun@ajisun-2 /> JCMD 36372 vm. uptime 36372:292.741sCopy the code
  • Output thread stack information (same as jstack command output)

    ajisun@ajisun-2 /> jcmd 36372 Thread.print
    ......
    "main" #1 prio=5 os_prio=31 tid=0x00007f8729808800 nid=0xe03 runnable [0x0000700002b67000]
       java.lang.Thread.State: RUNNABLE
      at com.ajisun.coding.ajisunmybatis.Allocation.main(Allocation.java:39)
    ​
    "VM Thread" os_prio=31 tid=0x00007f872a816800 nid=0x5003 runnable 
    ......
    Copy the code
  • Export heap information (same function as the jmap command)

    ajisun@ajisun-2 /> jcmd 36372 GC.heap_dump /Users/ajisun/Desktop/jvmTest/jcmd.txt
    36372:
    Heap dump file created
    Copy the code

As you can see from the JCMD 36372 help command, JCMD has many features, including the ability to override commonly used Jmap, and it is officially recommended to replace jmap with JCMD.

7. Jstat: vm statistics tool

The command tool used to monitor various running status information of virtual machines is relatively powerful and can be used to view heap information in detail.

Due to the length of this command, it will be covered in detail in the next article

Note: There will be an error in the middle of these commands

Error attaching to process: sun.jvm.hotspot.debugger.DebuggerException: Can’t attach symbolicator to the process

If you’re using a MAC, there’s nothing you can do about it, but ptrace_Scope is fine on Linux. Check the Internet for details.

The original address


I am Mr. Ji, with the output force input and continue to learn, continue to share the series of technical articles, as well as the whole network worth collecting good articles, welcome to pay attention to the public number, do a continuous growth of technical people.

Personal website

The JVM virtual machine series historical articles

1. Virtual Machine series: how to divide JVM runtime heap memory;

2. Virtual Machine series: Garbage collection algorithm in JVM;

3. Virtual Machine Series: JVM runtime data area;

4. Virtual Machine series: creation of objects in JVM, memory layout and access location;

5. Virtual Machine series: garbage collector in JVM;

6. Virtual Machine series: Memory allocation in the JVM;

7. Vm series: Understand VM logs and log parameters.