03_heap+MAT tool

The relationship between the stack method area:

HotSpot uses pointers to access objects:

  • The address for accessing class metadata is stored in the Java heap

  • The reference stores the address of the object

Three JVMs:

  • Sun's HotSpot
  • BEA's JRockit
  • IBM's J9 VM

1. Overview of heap system

Before Java7

Heap heap : There is only one heap memory in a JVM instance, and the size of the heap memory can be adjusted. After the class loader reads the class file, it needs to put the class, method, and constant variable into the heap memory, and save the real information of all reference types to facilitate execution by the executor. The heap memory is logically divided into three parts:

  • Young Generation Space Young/New

  • Tenure generation space Old/Tenure

  • Permanent Space Perm

Also known as: new generation (young generation), old generation, permanent generation (permanent generation).

The JVM heap is divided into the new generation and the old generation

1. The new area

The nascent area is the area where objects are born, grow, and die. An object is created here, applied, and finally collected by the garbage collector to end its life. The new space is divided into two parts: Eden space (Eden space) and survivor space (Survivor pace), all objects are new out in the Eden space. There are two survivor areas: Area 0 (Survivor 0 space) and Area 1 (Survivor 1 space). When the space in Eden runs out and the program needs to create objects again, the garbage collector of the JVM will perform garbage collection ( Minor GC ) on the Eden area to destroy objects in the Eden area that are no longer referenced by other objects. Then move the remaining objects in Eden to Survivor 0. If the surviving area 0 is also full, the area will be garbage collected and then moved to area 1. What if District 1 is also full? Garbage collection again, and then move to the retirement area after meeting the conditions. If the old-age area is also full, then MajorGC (FullGC) will be generated at this time to clean up the memory in the old-age area. If the old district executes the Full GC and finds that the object cannot be saved, an OOM exception "OutOfMemoryError" will be generated.

If java.lang.OutOfMemoryError: Java heap space exception occurs, it means that the heap memory of the Java virtual machine is not enough. There are two reasons:

(1) The heap memory setting of the Java virtual machine is not enough, which can be adjusted by the parameters -Xms and -Xmx.

(2) A large number of large objects are created in the code and cannot be collected by the garbage collector for a long time (there are references).

2. Old generation

Objects that still exist after multiple GCs (the default is 15 times), objects in the old generation are relatively stable and will not be GCed frequently

3. Permanent generation

The permanent storage area is a resident memory area, which is used to store the metadata of the Class and Interface carried by the JDK itself, that is to say, it stores the class information necessary for the operating environment, and the data loaded into this area will not be If the garbage collector reclaims it, the memory occupied by this area will be released only after the JVM is closed.

If java.lang.OutOfMemoryError: PermGen space appears, it means that the Java virtual machine does not set enough permanent generation Perm memory. Generally, this situation occurs because the program starts to load a large number of third-party jar packages. For example: Too many applications are deployed under one Tomcat. Or a large number of classes generated by dynamic reflection are continuously loaded, eventually causing the Perm area to be full.

Jdk1.6 and before: There is a permanent generation, and the constant pool 1.6 is in the method area

Jdk1.7: There is a permanent generation, but it has been gradually "removed from the permanent generation", and the constant pool 1.7 is in the heap

Jdk1.8 and later: no permanent generation, constant pool 1.8 in Metaspace

In fact, the method area (Method Area), like the heap, is a memory area shared by each thread. It is used to store the virtual machine loaded: class information + ordinary constants + static constants + compiled code by the compiler, etc., although The JVM specification describes the method area as a logical part of the heap, but it also has an alias called Non-Heap (non-heap), which is intended to be separated from the heap.

For the HotSpot virtual machine, many developers are used to calling the method area "Permanent Gen", but strictly speaking, the two are different in essence, or use the permanent generation to implement the method area, and the permanent generation is the method area ( It is equivalent to an implementation of an interface interface). In the jdk1.7 version, the string constant pool originally placed in the permanent generation has been removed.

The constant pool is a part of the method area. In addition to the class version, field, method, interface and other description information in the Class file, there is another piece of information is the constant pool. This part of the content will enter the method area after the class is loaded. Stored in the runtime constant pool.

2. Getting Started with Heap Parameter Tuning

Both take JDK1.8+HotSpot as an example

jdk1.7:

jdk1.8:

-XX:MetaspaceSize This parameter is the initial Metaspace size

-XX:MaxMetaspceSize specifies the maximum size of the metadata area.

1. Commonly used JVM parameters

How to tune jvm? Configured by parameters

parameter Remark
-Xms The initial heap size. As long as it is started, the heap size occupied, the default is 1/64 of the memory
-Xmx Maximum heap size. The default is 1/4 of the memory
-Xmn Young area heap size
-XX:+PrintGCDetails Output detailed GC processing logs

The java code checks the default size of the jvm heap:

Runtime.getRuntime().maxMemory() // The maximum value of the heap, the default is 1/4 of the memory
Runtime.getRuntime().totalMemory() // The current total size of the heap, the default is 1/64 of the memory

2. How to set JVM parameters

When the program is running, you can set jvm parameters for the program, and different tools have different setting methods.

If running from the command line:

java -Xmx50m -Xms10m HeapDemo

The eclipse run is set up like this:  

The setting method of idea runtime is as follows:

3. View heap memory details

public class Demo2 {
    public static void main(String[] args) {

        System.out.print("最大堆大小:");
        System.out.println(Runtime.getRuntime().maxMemory() / 1024.0 / 1024 + "M");
        System.out.print("当前堆大小:");
        System.out.println(Runtime.getRuntime().totalMemory() / 1024.0 / 1024 + "M");
        System.out.println("==================================================");

        byte[] b = null;
        for (int i = 0; i < 10; i++) {
            b = new byte[1 * 1024 * 1024];
        }
    }
}

Configuration parameters before execution: -Xmx50m -Xms30m -XX:+PrintGCDetails

Execution: see the following information

The sum of the heap sizes of the new generation and the old generation is Runtime.getRuntime().totalMemory()

4. GC Demo

public class HeapDemo {

    public static void main(String args[]) {

        System.out.println("=====================Begin=========================");
        System.out.print("最大堆大小:Xmx=");
        System.out.println(Runtime.getRuntime().maxMemory() / 1024.0 / 1024 + "M");

        System.out.print("剩余堆大小:free mem=");
        System.out.println(Runtime.getRuntime().freeMemory() / 1024.0 / 1024 + "M");

        System.out.print("当前堆大小:total mem=");
        System.out.println(Runtime.getRuntime().totalMemory() / 1024.0 / 1024 + "M");

        System.out.println("==================First Allocated===================");
        byte[] b1 = new byte[5 * 1024 * 1024];
        System.out.println("5MB array allocated");

        System.out.print("剩余堆大小:free mem=");
        System.out.println(Runtime.getRuntime().freeMemory() / 1024.0 / 1024 + "M");

        System.out.print("当前堆大小:total mem=");
        System.out.println(Runtime.getRuntime().totalMemory() / 1024.0 / 1024 + "M");

        System.out.println("=================Second Allocated===================");
        byte[] b2 = new byte[10 * 1024 * 1024];
        System.out.println("10MB array allocated");

        System.out.print("剩余堆大小:free mem=");
        System.out.println(Runtime.getRuntime().freeMemory() / 1024.0 / 1024 + "M");

        System.out.print("当前堆大小:total mem=");
        System.out.println(Runtime.getRuntime().totalMemory() / 1024.0 / 1024 + "M");

        System.out.println("=====================OOM=========================");
        System.out.println("OOM!!!");
        System.gc();
        byte[] b3 = new byte[40 * 1024 * 1024];
    }
}

The jvm parameter is set to a maximum heap memory of 100M, and the current heap memory is 10M: -Xmx100m -Xms10m -XX:+PrintGCDetails

Run again, you can see minor GC and full GC logs:

5. OOM demo

Change the jvm parameter in the above case to the maximum heap memory setting to 50M, and the current heap memory setting to 10M, and execute the test: -Xmx50m -Xms10m

=====================Begin===========================
Maximum heap size: Xmx=44.5M
remaining heap size: free mem=8.186859130859375M
current heap size: total mem=9.5M
=================== First Allocated========= ============
5MB array allocated
remaining heap size: free mem=3.1868438720703125M
current heap size: total mem=9.5M
================Second Allocated======================
10MB array allocated
remaining heap size: free mem=3.68682861328125M
current heap size: total mem=20.0M
======== ==============OOM===========================
OOM!!!
Exception in thread "main" java .lang.OutOfMemoryError: Java heap space
    at com.atguigu.demo.HeapDemo.main(HeapDemo.java:40)

How to locate this error message in actual development? MAT tool

3. MAT tool

Installation method: eclipse plug-in market download

1. Use of MAT tools

Running parameters: -Xmx30m -Xms10m -XX:+HeapDumpOnOutOfMemoryError

Refresh the project: see the dump file

Open:

2. idea analysis dump file

Change the running parameters in the above example to:

-Xmx50m -Xms10m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=D:\tmp 

-XX:HeapDumpPath: Generate dump file path.

Execute again: generate C:\tmp\java_pid20328.hprof file

How to open the generated file? jdk comes with an interpretation tool for this type of file: jvisualvm.exe

Double click to open:

File --> Load --> Select the file to open

After loading:

4. Commonly used command lines (understand)

View java process: jps -l

View all parameters of a java process: jinfo process number

View summary garbage collection statistics for a java process: jstat -gc process number

S0C: Size of Survivor 0
S1C: Size of Survivor 1
S0U: Used size of Survivor 0
S1U: Used size of Survivor 1
EC: Size of Eden EU: Used size OC
of Eden
: Old generation size
OU: Old generation usage size
MC: Method area size
MU: Method area usage size
CCSC: Compressed class space size
CCSU: Compressed class space usage size
YGC: Young generation garbage collection
times YGCT: Young generation garbage collection consumption time
FGC : Old generation garbage collection times
FGCT: Old generation garbage collection consumption time
GCT: Garbage collection consumption total time

Guess you like

Origin blog.csdn.net/qq_45037155/article/details/130880976