Use of JvisualVM [reprinted] and reprinted by jvisualvm

Source: Internet
Author: User

Use of JvisualVM [reprinted] and reprinted by jvisualvm

VisualVM is a free visualization tool that integrates multiple JDK command line tools. It provides powerful analysis capabilities and performs Performance Analysis and Optimization on Java applications. These functions include generating and analyzing massive data volumes, tracking memory leaks, monitoring the Garbage Collector, executing memory and CPU analysis, and supporting browsing and operations on MBeans. This document describes how to use VisualVM For performance analysis and optimization.

It has been a part of Oracle JDK since JDK 6 Update 7 and is located in the bin folder of the JDK root directory. You can directly run it without installation.

 

VisualVM helps us analyze memory usage by detecting classes and Object Information loaded in the JVM. We can use the monitoring labels of VisualVM to analyze the memory of the application.

1) memory Heap

First, let's take a look at the Heap usage of the memory Heap. The process of eclipse on my local machine is displayed in visualVM as follows:

 

Write a program that occupies a large amount of memory. Run it.

The procedure is as follows:

package jvisualVM;public class JavaHeapTest {    public final static int OUTOFMEMORY = 200000000;        private String oom;    private int length;        StringBuffer tempOOM = new StringBuffer();    public JavaHeapTest(int leng) {        this.length = leng;               int i = 0;        while (i < leng) {            i++;            try {                tempOOM.append("a");            } catch (OutOfMemoryError e) {               e.printStackTrace();               break;            }        }        this.oom = tempOOM.toString();    }    public String getOom() {        return oom;    }    public int getLength() {        return length;    }    public static void main(String[] args) {        JavaHeapTest javaHeapTest = new JavaHeapTest(OUTOFMEMORY);        System.out.println(javaHeapTest.getOom().length());    }}

View the VisualVM Monitor tab, and the heap memory becomes larger.

 

Before running the program, click Heap Dump. Wait for a while and get the dump result. You can see some Summary information.

Click Classes and find that char [] occupies the largest memory.

 

Double-click it to obtain the following Instances result:

Instances are arranged in ascending order of Size.

The first one is the largest. Expand the values in the Field area.

The global variable tempOOM of the StringBuffer type occupies a very large amount of memory. Note that local variables cannot be obtained through heap dump.

In addition, for "heap dump", this function is not available for remote jvm monitoring. It is only available for local monitoring.

 

2) permanently retain the region PermGen

Next, let's take a look at the use of PermGen in the permanent reserved area.

Run the program loaded by a class. The Code is as follows:

package jvisualVM;import java.io.File;import java.lang.reflect.Method;import java.net.MalformedURLException;import java.net.URL;import java.net.URLClassLoader;import java.util.ArrayList;import java.util.List;public class TestPermGen {        private static List<Object> insList = new ArrayList<Object>();    public static void main(String[] args) throws Exception {        permLeak();    }    private static void permLeak() throws Exception {        for (int i = 0; i < 1000; i++) {            URL[] urls = getURLS();            URLClassLoader urlClassloader = new URLClassLoader(urls, null);            Class<?> logfClass = Class.forName("org.apache.commons.logging.LogFactory", true,urlClassloader);            Method getLog = logfClass.getMethod("getLog", String.class);            Object result = getLog.invoke(logfClass, "TestPermGen");            insList.add(result);            System.out.println(i + ": " + result);        }    }    private static URL[] getURLS() throws MalformedURLException {        File libDir = new File("C:/Users/wadexu/.m2/repository/commons-logging/commons-logging/1.1.1");        File[] subFiles = libDir.listFiles();        int count = subFiles.length;        URL[] urls = new URL[count];        for (int i = 0; i < count; i++) {            urls[i] = subFiles[i].toURI().toURL();        }        return urls;    }    }

After a type is loaded, a corresponding java. lang. class instance. This instance is stored in the heap like a common object instance. I think this is a special instance, to some extent, it acts as a proxy for accessing type information in the PermGen region.

 

After running for a while, an OutOfMemoryError is thrown. The VisualVM monitoring result is as follows:

 

Conclusion: The heap space allocated in the PermGen area is too small. We can solve this problem by setting the-XX: PermSize parameter and the-XX: MaxPermSize parameter.

For in-depth analysis of PermGen OOM, see http://www.cnblogs.com/zhuxing/articles/1247621.html

For more information about Perform GC, see this article.

This part of knowledge is more in-depth, and we need to continue research if we have time.

 

The main purpose of CPU performance analysis is to count the call status and execution time of the function, or, more simply, to count the CPU usage of the application.

The CPU usage when no program is running is shown as follows:

 

Run a CPU-consuming applet. The Code is as follows:

Package jvisualVM; public class MemoryCpuTest {public static void main (String [] args) throws InterruptedException {cpuFix ();} /*** fixed cpu running percentage ** @ throws InterruptedException */public static void cpuFix () throws InterruptedException {// 80% share of int busyTime = 8; // 20% share of int idelTime = 2; // start time long startTime = 0; while (true) {// start time startTime = System. currentTimeMillis ();/** running time */while (System. currentTimeMillis ()-startTime <busyTime) {;}// rest time Thread. sleep (idelTime );}}}

View the Monitor tab on the monitoring page

 

High CPU usage may be caused by inefficient code in our project;

When we put pressure on the program, too low CPU usage may also be a problem with the program.

 

Click Sampler in the Sampler and click "CPU" to start the CPU performance analysis session. VisualVM detects all called methods of the application,

Under the CPU samples tab, we can see that our method cpufix () has the longest self-use time, for example:

Switch to the Thread CPU Time page. The main function occupies the longest CPU Time, for example:

 

 

Thread Analysis

Java can implement multi-threaded applications. When we debug a multi-threaded application or perform performance tuning after development, we often need to know the running status of all threads in the current program, whether deadlocks or hot locks occur, so as to analyze possible system problems.

In the Monitoring label of VisualVM, we can view real-time information such as the number of Live threads and Daemon threads in the current application.

 

Run a small program with the following code:

package jvisualVM;public class MyThread extends Thread{        public static void main(String[] args) {                MyThread mt1 = new MyThread("Thread a");        MyThread mt2 = new MyThread("Thread b");                mt1.setName("My-Thread-1 ");        mt2.setName("My-Thread-2 ");                mt1.start();        mt2.start();    }        public MyThread(String name) {    }    public void run() {                while (true) {                    }    }    }

 

Two more Live threads from 11 to 13

The number of Daemon threads increases from 8 to 10.

 

The thread tag of VisualVM provides three views, which are displayed in the timeline by default, for example:

We can see two threads in our run program: My-Thread-1 and My-Thread-2.

 

There are also two types of views: The table view and the detailed information view. Here, let's take a look at the detailed view of each Thread:

 

 

Let's look at another deadlock program to see if VisualVM can analyze it.

package jvisualVM;public class DeadLock {    public static void main(String[] args) {        Resource r1 = new Resource();        Resource r0 = new Resource();        Thread myTh1 = new LockThread1(r1, r0);        Thread myTh0 = new LockThread0(r1, r0);        myTh1.setName("DeadLock-1 ");        myTh0.setName("DeadLock-0 ");        myTh1.start();        myTh0.start();    }}    class Resource {        private int i;            public int getI() {            return i;        }            public void setI(int i) {            this.i = i;        }            }    class LockThread1 extends Thread {        private Resource r1, r2;            public LockThread1(Resource r1, Resource r2) {            this.r1 = r1;            this.r2 = r2;        }            @Override        public void run() {            int j = 0;            while (true) {                synchronized (r1) {                    System.out.println("The first thread got r1's lock " + j);                    synchronized (r2) {                        System.out.println("The first thread got r2's lock  " + j);                    }                }                j++;            }        }        }    class LockThread0 extends Thread {        private Resource r1, r2;            public LockThread0(Resource r1, Resource r2) {            this.r1 = r1;            this.r2 = r2;        }            @Override        public void run() {            int j = 0;            while (true) {                synchronized (r2) {                    System.out.println("The second thread got r2's lock  " + j);                    synchronized (r1) {                        System.out.println("The second thread got r1's lock" + j);                    }                }                j++;            }        }        }

 

Open the JVM Process Detected by VisualVM. We can see that this tab is flashing. VisualVM has detected an error in the DeadLock class under my package.

Switch to the Thread tab and you will see the Deadlock. Deadlock detected!

In addition, you can click the Thread Dump to perform further analysis. We will not go into details here. Interested readers can experiment on their own.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.