Deep understanding of Java Virtual Machine---virtual machine tools VISUALVM (19)

Source: Internet
Author: User
Tags cpu usage visualvm stringbuffer

VisualVM is a free, integrated visualization tool that integrates multiple JDK command-line tools to provide you with powerful analytical capabilities for performance analysis and tuning of Java applications. These features include generating and analyzing massive amounts of data, tracking memory leaks, monitoring the garbage collector, performing memory and CPU analysis, and it also supports browsing and manipulation on MBeans. This article mainly describes how to use VisualVM for performance analysis and tuning.

Directory:  Preparatory work
Memory Analysis Chapter memory heap heap Persistent zone PermGen CPU Analysis Thread analysis article reference

Preparatory work

Since JDK 6 Update 7 has been part of the Oracle JDK, it is located under the Bin folder of the JDK root directory, without the need to install and run directly.

Memory Analysis Chapter

VisualVM helps us analyze memory usage by detecting class and object information loaded in the JVM, and we can perform memory analysis of the application through the VisualVM Monitoring tab.

1) Memory heap Heap

First we look at the memory heap heap usage, and the process of my native eclipse is shown in VISUALVM as follows:

Write a small program that takes up a lot of memory and runs 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 VISUALVM Monitor tab, heap memory is getting bigger

Before the program runs, click the heap Dump button, wait for a moment, get the Dump result, you can see some summary information

Click Classes to find that char[] occupies the largest amount of memory

Double-click it to get the following instances results

Instances are arranged by size from large to small

The first one is the largest, expand the values of the field area

StringBuffer types of global variables tempoom occupy a large amount of memory, note that local variables can not be through heap dump to obtain the results of the analysis.

In addition, for "Heap dump", in the remote monitoring of the JVM, VISUALVM is not this function, only local monitoring.

# # #转载注明出处: http://www.cnblogs.com/wade-xu/p/4369094.html

2) permanently reserved area PermGen

Second, consider the use of permanent reserved areas PermGen

Run a class-loaded program with the following code:

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 <; 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 () throwsmalformedurlexception {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 is created, and the instance itself is stored in the heap like a normal object instance, which I think is a special instance, in part because it acts as a proxy for accessing type information in the PermGen region.

After running for a period of time to throw OutOfMemoryError, VISUALVM monitoring results are as follows:

Conclusion: The heap space of PermGen region allocation is too small, we can solve it by setting-xx:permsize parameter and-xx:maxpermsize parameter.

For an in-depth analysis of PermGen Oom, please refer to this article

For perform GC, please refer to this article

This part of the knowledge is still more in-depth, have time to continue to study.

# # #转载注明出处: http://www.cnblogs.com/wade-xu/p/4369094.html

CPU Analysis Chapter

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

CPU usage when no program is running such as:

Run a CPU-intensive applet with the following code

Package Jvisualvm;public class Memorycputest {public    static void Main (string[] args) throws Interruptedexception {
   cpufix ();    }    /**     * CPU Run fixed percentage     *      * @throws interruptedexception     *    /public static void Cpufix () throws interruptedexception {        //80% share        int busyTime = 8;        20% of the share        int ideltime = 2;        Start time        long startTime = 0;                while (true) {            //start time            startTime = System.currenttimemillis ();             /* * Run time *            /while (System.currenttimemillis ()-startTime < BusyTime) {                ;            }                        Break Time            Thread.Sleep (ideltime);}}}    

View Monitoring page Monitor tab

Excessive CPU utilization may be due to inefficient code in our projects;

When we put pressure on the program, too low CPU utilization could be a problem with the program.

Click on the Sampler sampler, click on the "CPU" button to start the CPU profiling session, VisualVM will detect all the methods that are called by the application,

In the CPU Samples tab can see our Method Cpufix () for the longest time, such as:

Switch to the Thread CPU time page, our main function this process consumes the longest CPU, such as:

# # #转载注明出处: http://www.cnblogs.com/wade-xu/p/4369094.html

Threading Analysis Chapter

The Java language enables multithreaded applications to be implemented very well. When we debug a multithreaded application or develop performance tuning later on, we often need to know the running state of all the threads in the current program, whether there are deadlocks, Jes, and so on, so as to analyze the possible problems of the system.

Within the VisualVM monitoring tab, we can view real-time information such as the number of active threads (live threads) and daemon threads (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 = NE W 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) {                    }    }}

Live threads increased from 11 to two to 13.

The Daemon threads increased from 8 to two and became 10.

VisualVM's thread label provides three views, which are displayed by default in the timeline, such as:

You can see two threads that are starting in our run Program: My-thread-1 and My-thread-2.

There are also two different views, the table view and the detail view, which look at the detailed view of each thread:

# # #转载注明出处: http://www.cnblogs.com/wade-xu/p/4369094.html

Another deadlock program, 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 VISUALVM detected JVM process, we can see this tab is flashing, VISUALVM has detected my package under the deadlock class error

Switch to Thread tab and you can see the deadlock, Deadlock detected!

You can also click the thread dump thread dump, further analysis, here will not repeat, interested readers can experiment on their own.

Reference documents:

http://www.ibm.com/developerworks/cn/java/j-lo-visualvm/

Transferred from: http://www.cnblogs.com/wade-xu/p/4369094.html

Deep understanding of Java Virtual Machine---virtual machine tools VISUALVM (19)

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.