[Java] threading and memory analysis tool VisualVM and MAT simple tutorial

Foreword

This article will briefly introduce the use of Java threads and memory analysis tool VisualVM and MAT, and further study may refer to the official website or tools to help (eg MAT: Help -> Welcome -> Tutorials), and mastery in practice.


VisualVM

Java VisualVM after JDK1.6 own visualization tool that provides a graphical interface to thread real-time monitoring applications, CPU and memory resource consumption, and can save snapshots for off-line analysis of performance bottlenecks in the program.

Installation and Configuration

After JDK1.6 already comes with VisualVM tool (jvisualvm.exe). If you use a non-Oracle JDK, free to log on the official website to download and install VisualVM.
After downloading the tool, you need to visualvm_143\etc\visualvm.confconfigure the JDK path (visualvm_jdkhome) in the manual.

VisualVM can monitor local or remote Java program. You need to start the JMX service on the server side when using the remote control. First, the increase in the startup parameters of the remote procedure follows JVM parameters :
-Djava.rmi.server.hostname=10.186.189.98(远程服务器IP地址) -Dcom.sun.management.jmxremote.port=8090(JMX远程监听端口) -Dcom.sun.management.jmxremote.ssl=false(禁用SSL) -Dcom.sun.management.jmxremote.authenticate=false(不启用用户认证)

Then restart the remote program. In this case, netstat -ano | findstr 8090(Windows) or netstat -anlp | grep 8090view (Linux) port is in Listening state, indicating that enables remote JMX connections.

In addition to using VisualVM tool alone, but it can also be integrated in the plug-in IDEA VisualVM Launcher. By File-> Setting-> Plugins -> Browers Repositrories search VisualVM Launcher install and reboot IDEA, menus and buttons will appear between the two methods:

VisualVM will choose the path After clicking the button, select the VisualVM executable file. After that, click on the start VisualVM will open a window.

Local use

This section describes exemplary interface functions in conjunction with the code of VisualVM. Sample code is as follows:

package thread;

public class InfiniteLoop {
    public static void main(String[] args) {
        Thread t1 = new Thread(new ImplicitLoop(), "ImplicitLoop");
        Thread t2 = new Thread(new ExplicitLoop(),"ExplicitLoop");
        t1.start();
        t2.start();
    }
}

class ExplicitLoop extends Thread {
    @Override
    public void run() {
        while (true) {
            System.out.println("I work hard!");
        }
    }
}

class ImplicitLoop extends Thread {
    @Override
    public void run() {
        for (byte i = 0; i < 150; i += 2) {  //此处因数值溢出导致死循环
            System.out.println("I've worked " + i + " hours!");
            if (i >= 120) {
                try {
                    System.out.println("I'll take a short break...");
                    Thread.sleep(20);
                    System.out.println("I wake up!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Check local start VisualVM monitoring information, the interface is as follows:

Local left side Java process "local (Local)" following the example contains InfiniteLoop, including the right to Overview (Overview), monitor (Monitor), threads (Threads), sampler (Sampler) such as tabs to show details .

Among them, the basic information Overview page to view the process, JVM startup parameters, system properties (same jinfo -sysprops <pid>) and other information.

Monitor page can view CPU, memory (heap space and dollars), class and threads of real-time line chart. Garbage collection (Perform GC) button to trigger the system GC, Heap Dump (Heap Dump) button to specify the directory in piles of raw dump (Dump) file.

Note that clicking heap Dump (Heap Dump) button will turn on automatically load generated dump file when a local monitor, and you need to copy the generated dump file on the remote host remote monitoring to the local then manually loaded. In addition, VisualVM very slow when loading analysis memory Dump files, we recommend the use of MAT to analyze memory Dump .

Thread details page to view the running time and the state of each thread. Thread Dump (Thread Dump) button to generate a thread dump file (class jstack <pid>).

FIG., The time line display in active threads running, sleeping (SLEEP), wait (o.wait), dwell (idle) and surveillance (synchronous blocking) state, and a more detailed observation of the thread state by the zoom button.
Threads inspectorPlug-ins can display single or multiple thread's stack. The figure only checked ImplicitLoop thread, the stack was understood that the obstruction in System.out.println("I've worked " + i + " hours!")the line - the implementation of the method will first lock! By the Refresh button to refresh the stack, you will find ImplicitLoop threads sometimes dormant.

Sampler page at a certain time interval for CPU, memory sampling, you can check out more CPU time or memory space occupied by the larger thread helps performance tuning. When CPU sampling, sample page provides CPU (the Samples CPU) and the CPU time thread (Thread CPU time) two sub-tabs, can be used in the former method is called time-consuming analysis chain, which can be used to compare thread CPU Processed .

VisualVM also provide a lot of useful plug-ins, such as Visual GC (see garbage collection state). By tool (Tools) - Download Plug> Plug (Plugins).

Remote monitoring

Click on the left VisualVM remotely (Remote) -> Add Remote Host (Add Remote Host), fill in the server IP address.

Then click on the remote host, right-click "Add JMX Connection (Add JMX Connection)", fill in the JMX port number and check the "does not require an SSL connection (Do not require SSL)".

Adding JMX connectors Right "open (the Open)" or simply double-click on the right panel monitor interface may be seen.

MAT

MAT (Memory Analyzer Tool) is a fast, feature-rich JAVA heap dump analysis tool that helps developers find memory leaks and reduce memory consumption.

scenes to be used

MAT common usage scenarios are as follows:

  • OOM (OutOfMemoryError exception), there are usually reasons:
    • The object is dead but can not automatically recovered by the garbage collector, memory leaks constantly - need to find the code and fix the leak location
    • Too long or too long holding state of the life cycle of a large number of objects - the outer space in addition to increasing heap allocation, consider optimizing logic or code storage structure
  • CPU load is finished, the thread deadlock (similar VisualVM)
  • Spy on the contents of memory objects, such as:
    • Troubleshooting Debug debugging environment does not allow printing or add logs
    • The existence of sensitive information such as passwords in clear text resident memory scanning

Installation and Configuration

From the official website to download the stand-alone tool MAT, MAT directory run directly after decompression MemoryAnalyzer.exe to start the MAT.

If the analysis of the dump file to be too large, it can increase the installed files in the directory MemoryAnalyzer.ini Xmx parameter values (default 1G). Note, Xmx value can not exceed the operating environment of system memory, otherwise it will start being given MAT Failed to create the Java Virtual Machine.

Obtain a heap dump file

MAT is a heap of static analysis tools, need to pre-fetch Java heap dump files (memory snapshots).

Students can heap dump file in the following ways:
1) an increase in the JVM startup parameters in the -XX:+HeapDumpOnOutOfMemoryErrorparameter is automatically generated in the working directory (user.dir) OOM occurs when the system java_pid<pid>.hprofdump file. By JVM parameters may also -XX:HeapDumpPath=<path>explicitly specify the storage path stack dump file.
2) If you do not want to wait until you get OOM error occurred heap dump file, you can add JVM parameters -XX:+HeapDumpOnCtrlBreakto use Ctrl + Break (Pause) button on the console to demand access to the heap dump file.
3) If the environment Jmap tools available, you can by jmap -dump:live,format=b,file=heap.bin <pid>obtained dump file command.
Which, pid is the process ID, live option forces the trigger before dumping a full GC (to reduce file size), file and directory names can be specified to produce documents.
Similarly, VisualVM, Jconsole and other JDK tools can also be used afterlife heap dump file.
4) MAT itself is also available heap dump file that File -> Acquire Heap Dump menu.

Analyze heap dump file

This section also describes in conjunction with code examples MAT common interface functions. Sample code is as follows:

package thread;

import java.util.*;

public class JavaHeapDump {
    private static List<String> smallArray = new ArrayList<>();
    private static List<byte[]> largeArray = new ArrayList<>();

    public static String getPassword() {
        char[] pw = {'A', 'd', 'm', 'i', 'n', '1', '2', '3'};
        return new String(pw);
    }

    public static void makeHeapOom() {
        for (int i = 0; i < 1000; i++) {
            smallArray.add(getPassword()); //smallArray.add(getPassword().intern());

            byte[] elems = new byte[1024 * 1024];
            Arrays.fill(elems, (byte)101);
            largeArray.add(elems);
            //largeArray.add(new byte[1024 * 1024]);
        }
    }

    public static void main(String[] args) {
        makeHeapOom();
    }
}

Compiled code to -Xms20m -Xmx20mrun (limit quickly OOM heap space) like JVM parameters, to obtain the following output:

D:\xywang\target\classes>java -Xms20m -Xmx20m -Xmn2m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=E:\dump\heapDump.bin thread.JavaHeapDum
p
java.lang.OutOfMemoryError: Java heap space
Dumping heap to E:\dump\heapDump.bin ...
Heap dump file created [21458899 bytes in 0.805 secs]
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at thread.JavaHeapDump.makeHeapOom(JavaHeapDump.java:18)
        at thread.JavaHeapDump.main(JavaHeapDump.java:26)

Shows that soon appeared out of memory ( java.lang.OutOfMemoryError: Java heap space), and generates heapDump.bin dump file in the E drive.

At this point start MAT, select the menu item File -> Open Heap Dump to load the heap dump file to be analyzed. After loading the file, select the pop-up wizard page memory leak analysis in accordance with the mode.

Leak Suspect Report is the default analysis reports there may be a potential memory leak generated, describes the proportion of memory-intensive problems in a pie chart, pie chart below are the details regarding potential problem analysis.


Click "Details" link, you can see the biggest culprits may cause memory overflow indeed largeArray! Here, " Shortest Paths To the Accumulation Point" As the show and which is connected to GC Root cause is currently Retained Heap occupy a large object can not be recovered.

Overview tab provides an overview Heap Dump, including heap of pie and Actions / Reports / Step by Step and other fast-access area.

Which, Histogram (heap histogram) provides a list of statistical memory occupied by objects of class grouping, the default sorted by descending a shallow heap class. Dominator Tree (tree disposable) displayed in the Object / Class reserved memory size of the sort result of the investigation can be used to cause other objects which objects can not be garbage collected. Top Consumers Dominator Tree is a graphical statistical data, respectively, according Object, Class, ClassLoader, Package and other dimensions do memory usage statistics. Top Components listed more heap space occupied by the component, and suggests memory consumption can be reduced.

The most commonly used Dominator Tree interface as an example:

the heap two ArrayList, and one of which takes up 96.57% of the memory. The following summarizes the main fields of the meaning of the figure:

Shallow Heap: the object itself occupied by memory size, the object does not contain its share of the referenced memory size. Shallow Heap array of objects is the sum of the size of the array elements, Shallow Heap non-array object is the sum of all the members of the object variable size.
Retained Heap: the size of the current object + current object can be referenced directly or indirectly to the sum of the sizes of the object, i.e., the current object is the GC of total memory freed from the Heap.
incoming references: class which is referenced in the current class, or in which the current object is referenced object.
outgoing references: all instances of the current class, or object referenced by the current object.

Select the Dominator Tree occupies the largest object in memory, the with incoming referencesview held by external objects it references.

Visible, take up a lot of content is the culprit largeArray. For a collection of objects, you can right-select Java Collections submenu do all kinds of sort and view. For example, FIG select Extract List Valuesto view largeArraythe content, the results are as follows:

Peeped memory value

JavaHeapDump sample code intention to use the password, the real business can be such sensitive information exists by OQL (Object Query Language) to troubleshoot memory.

OQL is a language based on javascript expressions, as will the class table, the class instance object as rows, as a member variable object field in the table, you can use SQL statements similar to the way Java heap inquiry the object. OQL syntax structure is as follows:

select <JavaScript expression to select>
from [ instanceof ] <class name="name">
[ where <JavaScript boolean expression to filter> ]

More OOL syntax, on the OOL page press F1 to view the help information.

OQL MAT clicking the button in the toolbar, open the OQL editor window, enter the query command by clicking the red exclamation mark button to query results are as follows:

. "*" Note that the equivalent SQL query wildcard "%" statement behind "Admin123" . Query results surprised to see "Admin123" Such a plaintext password!

By Merge Shortest Path to GC Rootswhether to GC Roots up view these passwords objects:

if the object is unreachable then the password is not permanent memory, visible figure password are permanent memory.

Heap dump files comparative analysis

The actual business scenarios heap memory objects may be very much, locating memory leaks, usually they need to be captured and comparative heap dump file has two moments. MAT following steps:
1) load the first stack dump file and open Histogram view.
2) Open Window -> Navigation History view, right histogram select Add to Compare Basket.

3) load a second heap dump files, also add to the Compare Basket.
4) Open the Window -> Compare Basket View, click Compare the Results (red exclamation upper right corner).

5) analysis and comparison of results Compared Tables years.

For example, in FIG. 1 # is the memory information storing passwords, less than # 0 creates a String object (which may be evidenced by the results OQL) using String.intern ().

In this manner quickly locate the object held before and after the increment operation, so as to further localize the specific culprits memory leaks.

to sum up

This article briefly describes the use of Java threads and memory analysis tool VisualVM and MAT, and further study may refer to the official website or tools to help (eg MAT: Help -> Welcome -> Tutorials), and mastery in practice. Really nothing to say ......

Guess you like

Origin www.cnblogs.com/clover-toeic/p/11553867.html