当前位置:网站首页>JVM memory and garbage collection-3-runtime data area / method area

JVM memory and garbage collection-3-runtime data area / method area

2022-07-08 01:58:00 xcrj

summary

  • The method area is logically continuous , Physically dispersible
  • Object references are in the stack (LV in ), The object entity is in the heap , The object class information is in the method area
    OOM,JVM Too many classes loaded
  • jdk7-java.lang.OutOfMemoryError: PermGen space,jdk8=+ava.lang.OutOfMemoryError: Metaspace
  • Load third party jar There are too many classes in the package ;tomcat Too many projects deployed ; There are too many dynamically generated reflection classes

Forever / Meta space

 Insert picture description here
Introduce
-jdk8 Used meta space , Abandoned the permanent generation

  • Metaspace uses local memory , Permanent generation uses virtual machine memory

Forever (jdk7-)

  • -XX:PermSize initial min Permanent generation size , The default is 20M+
  • -XX:MaxPermSize max Permanent generation size ,32 Bit machines default to 60M+,64 Bit machine is the default 80M+
  • JVM The class information loaded exceeds -XX:MaxPermSize Will report java.lang.OutOfMemoryError: PermGen space
  • Capacity expansion : Permanent memory is allocated first -XX:PermSize( Permanent generation of initial memory )》 Not enough 》 Expand the capacity until -XX:MaxPermSize( Meta space maximum memory )
  • Shrinkage capacity : Permanent generation memory after expansion 》 There are idle 》 Shrink until -XX:PermSize( Permanent generation of initial memory )

Meta space (jdk8+)

  • -XX:MetaspaceSize Initial Metaspace size , The default is 20M+
  • -XX:MaxMetaspaceSize max Metaspace size , The default is -1, There is no limit
  • Default -XX:MaxMetaspaceSize=-1 Under the circumstances , The virtual machine runs out of all available system memory , newspaper java.lang.OutOfMemoryError: Metaspace
  • Different from heap and permanent generation min size , Heap is the concept of warning line
  • -XX:MetaspaceSize It's the warning water line 》 Reach this warning water level 》 Just call FGC(Full GC) Recycle useless classes , Free meta space 》 Then reset “ Warning water level ”
  • Reset “ Warning water level ”:FGC Too little free space To improve properly -XX:MetaspaceSize It's the warning water line , Less than -XX:MaxMetaspaceSize
  • Reset “ Warning water level ”:FGC Too much free space Appropriate reduction -XX:MetaspaceSize It's the warning water line

Memory leaks and memory overflows

 Insert picture description here

Memory leak

Definition : You cannot recycle unwanted objects , Cause memory leaks ; A memory leak has no major impact ; The consequence of memory leak accumulation is memory overflow .

out of memory

Definition : Memory required by the program > The system allocates memory

Handle

The process :dump》eclipse memory analyzer》 Distinguish memory leaks / overflow
if - Memory leak : Check the leak object to GC Roots Reference chain of
if - out of memory : Optimize the code , Reduce the survival time of objects ; Check the heap parameters -Xms and -Xmx Is it the right size

Method area

Content

  1. JIT Code cache :
  • Cache machine language ( Translation of hotspot bytecode into machine language )
  1. Class information :
  • Type information
  • Methods information
  • Domain information (Field Information )
  1. Runtime constant pool :
  • contain String constant ( Different versions jdk Different positions of string constants )
  1. Static variables

Class information / Type information

Class head

  • Access modifier
  • Class full name ( Package name . Class name )
  • Immediate parents ( Full name ,interface and java.lang.Object No parent )
  • List of direct interfaces (java Multiple interfaces can be implemented )

Class information / Domain information

Domain header

  • Access modifier
  • type
  • Domain name

Class information / Methods information

Method head

  • Access modifier
  • Return type
  • Method name
  • Input parameter type , Number , The order

Methods the internal

  • Method bytecode
  • LV(abstract and native There is no way LV)
  • OS
  • Anomaly table

Static constant pool

brief introduction

  • constant pool table yes *class Part of the document , Store the literal and symbol references generated after compilation
  • constant pool table After being loaded by the class, it is stored in the runtime constant pool in the method area
  • javac compile *.java After the document *.class Constant pool in file
  • Will be public , Take out the things that may be used , Reduce *.class file size ,*.class Store the reference of the required symbol in the file
  • Static constant pools are not dynamic

Content

  • Literal ( String constant ,final Constant etc. )
  • Symbol reference ( type - Class head , Method - Method head , Domain - Domain header )

Runtime constant pool

  • be located *.class The static constant pool in the file is loaded by the class and stored in the runtime constant pool in the method area
  • When the class loading , Reference the symbols required by the class ( In the static constant pool ) Turn to the real address ( In the runtime constant pool )
  • Every class or interface maintains 1 Runtime constant pool , Constants in the runtime constant pool are accessed through real addresses
  • The runtime constant pool is dynamic , You can add new constants to it , for example String.intern() Method Add string constants to the runtime constant pool

evolution

 Insert picture description here
analysis

  • jdk7=+ Static variables and string constant pools are put on the heap , Because the method area does not recycle often , Static variables and string constants are often created and used

Forever To Meta space :

  • Permanent generation size is difficult to determine , Tuning is difficult
  • Permanent generation garbage collection is complex

Garbage collection

brief introduction

  • Garbage collection in the method area is difficult , In particular, the type of uninstall
  • Mainly recycling “ Obsolete constants in the runtime constant pool ” and “ Types that are no longer used ”
  • Java The virtual machine specification does not mandate garbage collection in the method area
  • FGC: Support garbage collection in the method area
  • ZGC(jdk11): Garbage collection in the method area is not supported
  • In the extensive use of bytecode ( Reflection , A dynamic proxy ,CGLib Equal bytecode framework ) And custom class loader ( Dynamic generation JSP,OSGI) Generally need JVM It has the ability to unload classes

Method area content

  • Literal ( String constant ,final Constant etc. )
  • Symbol reference ( type - Class head , Method - Method head , Domain - Domain header )

Recycling - Abandoned constants

  • Constants in the constant pool can be recycled as long as they are not referenced anywhere
  • Similar to recycling java Obsolete objects in the heap

Recycling - Symbol reference / type

  • There are no instances of this class and related derived subclasses in the heap && Of the class java.lang.Class The object is not referenced anywhere && The class loader that loads this class has been recycled .
  • It is difficult to achieve the above three conditions , At the same time meet the above 3 Only three conditions are allowed to be recycled

example

How many classes are loaded

Code

package xcrj;

/* *  Customize 1 How many classes will be loaded into each class  * */
public class VMFunClassNum {
    
    public static void main(String[] args) {
    
        System.out.println("start...");
        try {
    
            Thread.sleep(1000000);
        } catch (InterruptedException ie) {
    
            ie.printStackTrace();
        }
    }
}

command

#  compile 
javac -d D:\workspace\idea\JVMDemo\blog\target\classes\ -encoding UTF-8 VMFunClassNum.java
#  function 
java -classpath D:\workspace\idea\JVMDemo\blog\target\classes\ xcrj.VMFunClassNum

result
 Insert picture description here
Introduce

  • Discovery only defines 1 In the case of two classes , Still loaded in the method area 1612 Classes

Method area OOM

Code

package xcrj;

import com.sun.xml.internal.ws.org.objectweb.asm.ClassWriter;
import com.sun.xml.internal.ws.org.objectweb.asm.Opcodes;

/* * extends ClassLoader *  First set up  -XX:MetaspaceSize10m -XX:MaxMetaspaceSize10m * */
public class VMMethodOOM extends ClassLoader {
    
    public static void main(String[] args) {
    
        int count = 0;
        try {
    
            VMMethodOOM methodOOMTest = new VMMethodOOM();
            for (int i = 0; i < 10000; i++) {
    
                // establish ClassWriter object , Bytecode for production classes 
                ClassWriter classWriter = new ClassWriter(0);
                // Parameters from left to right : Version number 1.8, Access control , Class name , Package name , Parent class , Interface 
                classWriter.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, "Class" + i, null, "java/lang/Object", null);
                //byte[]
                byte[] code = classWriter.toByteArray();
                // Load bytecode , Generate Class The object is in the method area ; Such kind extends ClassLoader
                methodOOMTest.defineClass("Class" + i, code, 0, code.length);
                count++;
            }
        } finally {
     //  Do not catch exceptions , Whether it is abnormal or not, it will execute finally The code in 
            System.out.println(" Number of generated classes :" + count);
        }
    }
}

command

#  compile 
# -XDignore.symbol.file=true, close javac The default from the “ Symbolic file ” Read class in , Instead of from “rt.jar” Read class in 
javac -XDignore.symbol.file=true -d D:\workspace\idea\JVMDemo\blog\target\classes\ -encoding UTF-8 VMMethodOOM.java
#  function 
java -XX:MetaspaceSize=10m -XX:MaxMetaspaceSize=10m -classpath D:\workspace\idea\JVMDemo\blog\target\classes\ xcrj.VMMethodOOM

result
 Insert picture description here

Static constant pool

 Insert picture description here

  • # Numbers Is to link to the constant pool

tuning

Parameters

classification Parameters effect Suggest
jdk7=-, Forever -XX:PermSize=100m Initial permanent generation size no
jdk7=-, Forever -XX:MaxPermSize=100mmax Permanent generation size no
jdk8=+, Meta space -XX:MetaspaceSize=100m Initial Metaspace size , cordon , Set a large value to prevent insufficient space FGC yes
jdk8=+, Meta space -XX:MaxMetaspaceSize=100m Maximum Metaspace size , Default -1 no
原网站

版权声明
本文为[xcrj]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130541456771.html