Tool is introduced

The JDK /bin directory provides many JDK tools. You need to use these tools together with Linux commands to check the RUNNING status of the JVM and troubleshoot problems. This section records the use of common command-line tools and visual tools.

Command line tool

JPS: tool for vm process status

JPS: Mainly used to locate the PID of a Java process, the following example code

/** JPS -q: displays the process ID -m: displays the process ID, the name of the main class, and the parameters passed into main. -1: displays the process ID, the full name of the main class. -v: displays the process ID, the king class name, and the parameters passed into JWM: displays the process ID, the name of the main class (default) */
public class DEMO01 {
    public static void main(String[] args) throws IOException {
        System.out.println("jps");
        / / blockingSystem.in.read(); }}Copy the code

Jstat: a tool to monitor VM information

Jstat: On Linux, the first tool used to locate JVM performance issues at runtime. It is often used to check memory trends, GC status, class loading status, etc

Use format: jstat [option vmid [interval [s | ms] [count]]]

  • Option represents the detailed information about the VM to be queried. Mainly includes: class loading, garbage collection, runtime compilation

  • [protocol:][//] LvmID [@hostname[: port]/servername]

  • Interval Query interval

  • Count Number of queries

If interval and count are ignored, the command is executed only once. For example, jstat -gc 2101 500 5 indicates that the garbage collection status of the 2101 process is queried every 500ms. The command is executed five times

Example 1:

public class DEMO02 {
    public static void main(String[] args) throws IOException {
        System.out.println("jstat"); System.in.read(); }}Copy the code

S0C, S1C refers to the capacity of Survivor0 zone 1; S0U,S1U refers to the usage of the two surviving zones; C stands for Capacity and U stands for Used, which reflects the initial Capacity and usage of each area, as well as The Times and time of GC.

Example 2:

import java.io.IOException;

public class DEMO03 {
    // Start parameters: -xms20m -XMx20m -xmn10m -xx:+UseserialGC -xx:+ PrintGcDetails -verbose:gc
    public static void main(String[] args) throws IOException {
        final int _1MB = 1024 * 1024;
        byte[] b1 = new byte[_1MB];
        System.out.println("1...");
        System.in.read();

        byte[] b2 = new byte[2*_1MB];
        System.out.println("Two...");
        System.in.read();

        byte[] b3 = new byte[2*_1MB];
        System.out.println("Three..."); System.in.read(); }}Copy the code

Specify the DEMO03 runtime JVM parameters, set the heap to 20M and the new generation to 10M, and use the Serial garbage collector

It can be seen that the changes in Eden area occurred in the three printing times. YoungGC occurred once, and GC time was 0.015s

Jstack: View the Java thread stack information

Format: jstack [option] vmID

Example 1: an infinite loop AVA program that simulates crazy CPU usage in Linux

improt java.util.Random;
public class demo {

    public static void main(String[] args) {
        while(true){
            System.out.println(new Random().nextInt(77778888)); }}}Copy the code

Check the system status: use the top command to check the CPU and memory resource consumption of each process and find out the process PID that consumes the most resources. As shown in the figure, the process pid that consumes the most resources is the Java process, and its PID is 2818 [need to run in the background for a long time to respond…..]

Locate the faulty THREAD: Locate the faulty THREAD ps-mp pid-o THREAD,tid,time As shown in the figure, 2819 THREAD consumes the most resources in the Java process

Printf “%x\n” The id of the faulty thread is converted to lowercase in hexadecimal

In the use of jstack check thread stack information jstack pid | grep tid – A60

This is just a small demo to simulate the program dead loop, CPU line warning may occur many possibilities, common memory leaks, deadlocks, frequent GC… need to be based on Linux commands and Java commands and the actual situation of the step by step troubleshooting.

Jinfo: View and set vm parameters

Jinfo can view the PARAMETERS of the JVM and allows modification of the PARAMETERS of the JVM while the program is running so that the JVM does not need to be restarted.

Use format: jinfo [option] pid, can pass – flag [+ | -] name add and remove some of the parameters, or – flag name = value to modify some of the parameters, but many parameters are not allowed to modify

public class DEMO04 {
    public static void main(String[] args) throws IOException {
        System.out.println("jinfo"); System.in.read(); }}Copy the code

Jmap: Generates the dump file

Jmap is used to generate a dump, which exports a snapshot of the usage of the Java heap for troubleshooting.

The format is jmap [option] vmID

Example:

public class DEMO05 {
    public static void main(String[] args) throws IOException {
        System.out.println("jmap"); System.in.read(); }}Copy the code

Jmap-heap PID displays detailed information about the heap area

Jmap-dump :live,format=b,file=D:\jmap.bin pid generates binary files

Jhat: vm storage snapshot analysis tool

Once you have exported the snapshot file of the heap using JMap, you can use JHAT for analysis, although jHAT is less commonly used today.

Use the format: the jhat [- stack] [- refs] [port] – [- baseline] [- debug] [- version] [- h | -help]

Example:

Visualization tool

jconcle

Purpose: View Java application runtime, monitor garbage collector memory trends, and monitor threads within the program.

Example 1: JConsole demonstrates memory changes

public class DEMO07 {
    public static void main(String[] args) throws IOException, InterruptedException {
        Thread.sleep(5000);
        System.out.println("start....");
        test();

        System.in.read();
    }

    public static void test(a) throws InterruptedException {
        final int _128K = 128 * 1024;
        List<byte[]> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            // Time consuming operation to make the monitor curve change more obvious
            Thread.sleep(100);
            list.add(new byte[_128K]); }}}Copy the code

To start the JConsole, type jConsole

The JConsole client includes the overview, memory, threads, classes, VM profiles, and MBeans chunks.

Overview: An overview of the main running data, including heap memory, threads, classes, and CPU usage trends

Memory: Use the ParallerScavenge+Parallel Old garbage collector to monitor the heap insane, Survivor, and non-heap memory. Equivalent to jstat on the command line

Thread: you can view which threads are running in the current program. In a single machine, you can view the stack information of the thread, which is equivalent to the JStack of the command line tool. The bottom left corner of the button is also used to detect deadlocks.

Classes: The figure shows the system and the number of classes loaded. In the details bar, you also see the number of uninstalled classes.

VM Summary: VM Summary: On the VM Summary page, JConsole displays the environment in which the current application is running. The vm information includes vm type, version, heap information, and VM parameters. Equivalent to the jinfo command in the command line tool

Example 2: JConcle example deadloops, blocking waits, and deadlocks

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class DEMO08 {

    public static void main(String[] args) throws IOException {
        System.in.read();
        System.out.println("Start an infinite loop thread");
        whileTureThread();

        System.in.read();
        System.out.println("Start waiting thread");
        waitThread();

        System.in.read();
        System.out.println("Open a deadlock thread");
        deadLock();

    }

    /** ** the thread is dead loop */
    private static void whileTureThread(a) {
        new Thread(() -> {
            while (true) {}},"whileTrueThread").start();

    }

    /** ** Wait thread */
    private static void waitThread(a) {
        new Thread(() -> {
            synchronized (DEMO08.class) {
                try {
                    DEMO08.class.wait();
                } catch(InterruptedException e) { e.printStackTrace(); }}},"waitThread").start();
    }


    /** * Simulate deadlock */
    private static void deadLock(a) {
        String A = "A";
        String B = "B";
        new Thread(() -> {
            synchronized (A) {
                try {
                    / / sleep for 2 seconds
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (B) {
                    System.out.println("Get the B-lock."); }}},"A").start();

        new Thread(() -> {
            synchronized (B) {
                try {
                    / / sleep for 2 seconds
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (A) {
                    System.out.println("Get the A-lock."); }}},"B").start(); }}Copy the code

First, press Enter on the console to start the dead-loop thread and observe the CPU usage. It can be seen that the CPU usage remains high

When you go to the console and press Enter to open the waiting thread, you can observe the thread status and locate the specific line by viewing the stack information

After going to the console, press Enter to start the deadlock thread to observe the thread situation. By checking the stack information, it can be found that thread A is waiting for the lock of THREAD B, and thread B is waiting for the lock of thread A

The printing situation of the console is shown as follows:

visualvm

Again using the code from Example 2 in JConcle, this time enter jVisualVM at the terminal. Jvisualvm is used somewhat similarly to JConsole. First open the loop to observe its CPU usage, it can be seen that it is also high, and relatively stable.

View the waiting thread: yellow represents the waiting thread. Click on the thread Dump to view the stack information of the thread

View the deadlock thread, when the deadlock thread is enabled, VisualVM can immediately detect, click on the thread Dump, generate a snapshot file to view the stack details.

Refer to the link

JDK Common command line tool Dark Horse VM performance analysis tool