当前位置:网站首页>JVM Series 1: memory and garbage collection (2)

JVM Series 1: memory and garbage collection (2)

2020-12-07 17:49:41 There is a Fei

JVM Series of : Memory and garbage collection ( Two )

## This is an overview of this article :
1、 Pile up Heap Area
2、 Method area Method Area
3、 Run time data area summary 
4、 Object instantiation memory layout and access location 

One 、 Pile up Heap Area

1、 The core concept of the heap

· One JVM The instance has only one heap memory , So is heap Java The core area of memory management .

·Java The heap area is in JVM It is created at startup , The size of the space is determined . yes JVM The largest memory space managed .

· The heap can be in a physically discontinuous memory space , But logically, he should be seen as continuous .

· All threads share Java Pile up , Here you can also partition the thread private buffer TLAB(Thread Local Allocation Buffer)
【 So heap space is not completely shared , Because there's more TLAB】

· The size of heap memory can be adjusted : Initial heap space -Xms10m  Maximum heap space -Xmx10m


## explain :
 A process corresponds to a JVM example , One JVM The instance corresponds to a Runtime Data Area,
 A process corresponds to a heap and method area , A process has multiple threads , One for each thread PC register 、 Virtual machine stack and local method stack .
 therefore , The heap and method area are shared by multiple threads in the process .



· Almost all object instances   as well as   Array   Should be allocated on the heap at run time .

· Arrays and objects may never be stored on the stack , Because the stack frame saves the application , This reference points to the location of the object or array in the heap .

· At the end of the method , Objects in the heap will not be removed immediately , Only in the GC It's only removed when it's collected .

· Pile up , yes GC During the garbage collection period, the key areas where garbage collection is carried out 

## expand 
 The command to create an object in the heap  :  Create objects new   Create array newarray

2、 Memory subdivision of heap

## The heap space is subdivided into :

JDK7 And before : New Area  +  Retirement area   +   The permanent zone 

JDK8 And after : New Area  +  Retirement area   +   Meta space 

【 New Area  = Eden District  + Survivor District 】

( Most modern garbage collectors are designed based on generational collection theory )

 name :  New Area  =  The new generation  =  The younger generation 
       Retirement area  =  Old age area  =  Old age 
       The permanent zone  =  Forever 

3、 Set the heap memory size with OOM

·Java The heap is used to store Java Object instances , So the size of the heap is JVM It's set when it starts .

 Can pass -Xmx -Xms To set it up :
> -Xms Indicates the starting memory of the heap , Equivalent to -XX:InitialHeapSize
> -Xmx Represents the maximum memory in the heap , Equivalent to -XX:MaxHeapSize

· Once the memory size in the heap exceeds -Xmx The maximum memory specified , Will throw OutOfMemoryError abnormal 

· Usually will -Xms  and  -Xmx  Both parameters are configured with the same value :
 The aim is to be able to java After the garbage collection mechanism cleans up the heap, it does not need to re partition and calculate the size of the heap , To improve performance .
( The starting memory of the heap   If   It's not equal to   Maximum heap memory , In the process of use, it will continue to   Capacity expansion   and   Release , Creating unnecessary system pressure , Also avoided GC After the re partition heap size )

· By default 
 Initial memory size  =  Physical computer memory size  / 64
 Maximum memory size  =  Physical computer memory size  / 4

## expand :
-X  yes JVM Operation parameters of   ms yes memory start

## View set parameters : 
 Mode one :  Check the process jps  /    Check memory usage  jstat -gc  process ID
 Mode two :-XX:+PrintGCDetails     Print GC details 
[ When heap objects are stored  Eden + s0 or s1   Survivors area s0 and s1 Only one of them can be used ]


## The figure below S0 S1 It means the survivor area 0 and 1,S0U S1U The survivor area is use Use size 
##EC and EU It means garden of Eden Eden The size of the area 

4、 The new generation and the old generation

· Stored in JVM Medium Java Objects can be divided into two categories :
> One is transient objects with short life cycle , The creation and death of such objects are very rapid 
> Another kind of object has a very long life cycle , In some extreme cases, it can also be associated with JVM The declaration cycle of the .

·Java If the heap area is further subdivided , Can be divided into  " The younger generation "(YoungGen)  and  " Old age "(OldGen)

· among  " The younger generation "  And we can divide it into : Eden Space 、Survivor0 Space 、Surivivor1 Space ( Sometimes it can be called from District 、to District )

· The following parameters will not be adjusted in the development ---- The proportion of the new generation and the old generation in the stack structure is configured :

> Default -XX:NewRatio=2, The new generation occupies 1, The old generation occupies 2, The Cenozoic took over the whole pile 1/3
> You can modify -XX:NewRatio=4, The new generation occupies 1, The old generation occupies 4, The Cenozoic took over the whole pile 1/5


· stay HotSpot in ,Eden Space   and   The other two Survivor The proportion of space is 8:1:1

· Of course, developers can use the option  -XX:SurvivorRatio  Scale the space .
 Such as :-XX:SurivivorRatio=8

· Almost all Java It's all about Eden Quilt new Coming out .

· Most of them Java Object's   The destruction   It's all in   The new generation   the (80%)

· Options available  "-Xmn"  Set the new generation maximum memory size 
> This parameter usually uses the default value ( If set at the same time -XX:NewRatio, With -Xmn Subject to )

·JVM On by default   The adaptive   Memory allocation policy 
> We can go through  -XX:-UseAdaptiveSizePolicy  To turn off adaptive 
[-XX:+UseAdaptiveSizePolicy Said the use of   -XX:-UseAdaptiveSizePolicy Means closing ]


5、 The process of allocating objects

1> new First put the object of Eden Park . This area has a size limit 

2>  When Eden's space fills up , At this point, the program needs to create the object ,JVM Our garbage collector will recycle the garbage of Eden Park (Minor GC / YGC).
 Destroy objects in the Eden Garden that are no longer referenced by other objects . Then load the new object and put it in the garden of Eden .
( Garbage collection period GC when ,STW[Stop the World],Java All other threads of the application are suspended , To facilitate the garbage collector to determine who should be recycled )
【 Eden is full and triggers YGC, however S0S1 The survivor zone is full and doesn't trigger YGC, It's going to go straight to the old days 】

3>  Then move the remaining objects in Eden to the survivors 0 District 

4>  If garbage collection is triggered again , At this point, the last survivor is placed in the survivor 0 District , If not recycled , It's going to put the survivors 1 District . At the same time, the survivors of Eden Park are also placed in the survivors 1 District .

5>  If you go through garbage collection again , At this point, the survivors will be replaced 0 District ( So are the Eden survivors ), Then go to the survivors 1 District ( So are the Eden survivors )

6>  When can I go to the nursing home ? You can set the number of times : The default is 15 Time 
     Parameters -XX:MaxTenuringThreshold=<N> Set it up 

7>  In the old age , Relatively leisurely . When the old days ran out of memory , Set out again GC(Major GC), Clean up the memory in the elderly area .
        
8>  If the elderly area has implemented Major GC Later, it was found that the object could not be saved , It will produce OOM abnormal 
    (java.lang.OutOfMemoryError : Java heap space)
        

## summary :

· Survivor S0S1 District , After copying, there is exchange , Who is empty and who is to

· About recycling : Frequent collection of , It's rarely collected in the retirement area , Several times not in the permanent zone / Meta space collection 

## expand : Common tuning tools 

·JDK command :jinfo  jstat  jmap  javap etc. 
·Eclipse:Memory Analyzer Tool
·Jconsole
·JVisualVM
·Jprofiler
·Java Flight Recorder
·GCViewer
·GC Easy

6、Minor GC、Major GC And Full GC

·JVM It's going on GC when , Not every time the above three memory areas are recycled together ( The new generation 、 Old age 、 Method area ),
 Most of the time it's recycled   The new generation 

· in the light of HotSpot VM The implementation of the ,GC According to the recycling area, it can be divided into two types : Part of the collection (Partial GC) Collect the whole pile (Full GC)

> Part of the collection : Not the whole collection JAVA Garbage collection . It is subdivided into :
 Cenozoic collection (Minor GC/Young GC): It's just a new generation of garbage collection 
 Old age collection (Major GC/Old Gc): It's just garbage collection in the old days 
 Mixed collection (Mixed GC): Collecting garbage from the whole new generation and part of the old age 
[ Be careful : Only CMS GC There will be separate collection of old age behavior ]
[ Be careful : A lot of times Major GC Hui He Full GC Mix it up and use it together , We need to distinguish between old age recycling and whole heap recycling ]
[ Be careful : Only G1 GC There will be Mixed GC]

> Collect the whole pile (Full GC): Collect the whole Java Garbage collection in the heap and method area 




·Minor GC( The younger generation GC) Trigger mechanism :
> When there was not enough space for the younger generation , Will start Minor GC, The young generation here means Eden Daiman ,Survivor Can't start GC( Every time Minor GC Will clean up the memory of the younger generation )
> because Java Most of the objects are born and die at the same time , therefore MinorGC Very often , Generally, the recycling speed is also relatively fast .
>Minor GC May trigger STW, Pause other users' threads , And so on , The user thread is restored .


·Major GC( Old age GC) Trigger mechanism :
>Major GC Refers to what happened in the old days GC, Objects are cleaned up from the older generation .
> appear Major GC, It will always be accompanied at least once Minor GC( But not absolutely )
[ That is, when the elderly are short of space , Will try to start Minor GC. If there is not enough space after that, start Major GC]
>Major GC It's usually faster than Minor GC slow 10 More than times ,STW Longer time .
> If Major GC after , There is not enough memory , Report on OOM.


·Full GC Trigger mechanism :
> Trigger Full GC There are five cases as follows :
①、 call System.gc() when , System execution Full GC, But not necessarily 
②、 There is not enough space in the old age 
③、 Insufficient method space 
④、 Yes Eden District 、S0 District direction S1 When copying , The object size is greater than S1 Available memory , Then transfer the object to the old age , And the available memory in the old days was smaller than the object size .
[ Be careful :Full GC It's something that should be avoided in development or tuning , It'll be shorter for a while ]


7、 The idea of heap space generation

## Why do you need to put JAVA Heap generation ? Can't work without generations ?

· After research , Different objects have different declaration cycles .70%~90% The object of is a temporary object .
> The new generation : Yes Eden、 Two of the same size Survivor constitute 
> Old age : Storage in the Cenozoic has experienced many times GC Objects that are still alive 

· In fact, part of the belt can be , The only reason for generations is to optimize GC performance .
 If there are no generations , All the objects are in one place , It's like a school where people are locked up in a classroom .GC When you look for 
 Which objects are useless , This will scan all areas of the heap . And a lot of people are living and dying , If the generational 
 word , Put the newly created object somewhere , When GC When you store this piece first   transient   The area of the object is returned to 
 closed , This will make a lot of space 

8、 Memory allocation policy

· If the object is Eden Born and passed by once MinorGC Still alive after , And can be Survivor If it can be accommodated , Will be 
 Move to Survivor In the space , And set the target age to 1. The object is Survivor Every time I get through the area MinorGC,
 Age increases 1 year , When its age increases to a certain extent ( Default 15) when , Will be promoted to the old age .
[ The age threshold of the age at which the target is promoted to the old age , Can pass -XX:MaxTenuringThreshold To set up .]

· The principle of object allocation for different age groups is as follows :
> Give priority to Eden
> Large objects are directly allocated to the old age 
	[ Try to avoid too many large objects in the program ]
	[ As big as Eden There's no room left in the area , It can only be put directly into   Old age area ]
> Long lived objects are assigned to old age 
> Dynamic object age determination 
	 If s The combined size of all objects of the same age in the region is larger than s The general of space , A pair older than or equal to that age 
 Elephants can go straight into the old age , No need to wait MaxTenuringThreshold The age required in 
> Space allocation guarantee 
	-XX:HandlePromotionFailure


### Space allocation guarantee :

 In the event of a Minor GC  Before , Virtual opportunity checks whether the largest available continuous space of the old generation is larger than the total space of all objects of the new generation .
> If it is greater than , This time Monor GC Is safe 
> If it is less than , Then virtual opportunity view -XX:HandlePromotionFailure Whether the set value allows the guarantee to fail 
 If HandlePromotionFailure=true,name It will continue to check whether the maximum possible continuous space of the elderly is larger than the average size of the objects who have been promoted to the old age .
√ If it is greater than , Then try to do Minor GC, But this time Minor GC There are still risks 
√ If it is less than , It's going to be one time Full GC
 If HandlePromotionFailure=false, It's going to be one time Full GC

 stay JDK6 Update24 after ,HandlePromotionFailure The parameters no longer affect the space allocation guarantee policy of the virtual machine . The rules changed to   As long as the continuous space of the old age is larger than the total size of the new generation object   perhaps   All previous promotions will be carried out MinorGC, Otherwise, it will be FullGC

9、 Object allocation process :TLAB

## What is? TLAB?
· From the perspective of memory model, not garbage collection , Pile up Eden Areas continue to be divided ,JVM Each thread is allocated a private buffer area , It is contained in Eden In space .
· Multithreading allocates memory at the same time , Use TLAB It can avoid a series of non thread safety problems , At the same time, it can also improve the memory 
 Allocated throughput , So we can call this method of memory allocation   Fast allocation strategy 
·OpenJDK derived JVM All offer TLAB Design .


## Why TLAB(Thread Local Allocation Buffer)?
· The heap is a thread shared area , Any thread can access the shared data in the heap 
· Because the object instance is created in JVM Very often , Therefore, it is not thread safe to divide memory space from heap in concurrent environment 
· In order to avoid multiple threads operating on a unified address , You need to use mechanisms like locking , And then affect the distribution speed , So there must be TLAB


##TLAB explain 
· Not all object instances are sufficient in TLAB Successfully allocated memory in , but JVM It's going to be TLAB As the first choice for memory allocation 
· In the program , Can pass -XX:UseTLAB Set whether to turn on TLAB( Default on )
· By default ,TLAB The memory of the space is very small , The whole stack Eden Spatial 1%, Of course, we can 
-XX:TLABWasteTargetPercent Set up TLAB Space takes up Eden Space percentage size 
· Once the object is in TLAB When space allocation fails ,JVM Will try to use   Lock mechanism   Ensure the atomicity of data operations , So directly in Eden Allocate memory in space .

10、 Heap space parameters

-XX:+PrintFlagsInitial	 View the default initial values of all parameters 
-XX:+PrintFlagsFinal	 See the final values of all the parameters 
	 The specific command to view a parameter :jps  View the currently running process 
						jinfo -flag SurvivorRatio  process ID
-Xms	 Initial heap space memory ( Default in room memory 1/64)
-Xmx	 Maximum heap space memory ( Default in room memory 1/4)
-Xmn	 Setting the size of the new generation ( Initial value and maximum value )
-XX:NewRatio	 The proportion of the new generation and the old generation in the stack structure is configured 
-XX:SurvivorRatio	 Configure the new generation of Eden and S0/S1 The proportion of space 
-XX:MaxTenuringThreshold	 Set the maximum age for the new generation of garbage 
-XX:+PrintGCDetails	 Output GC Processing logs 
	 Print GC Brief information :-XX:+PrintGC  -verbose:gc
-XX:HandlePromotionFailure	 Set up space allocation guarantee 

11、 Is heap the only way to allocate object storage ?

 If the escape analysis reveals , If an object has no way to escape , Then it may be optimized to be allocated on the stack .

· How to allocate objects on the heap to the stack , Need to use escape analysis 
· This is an effective way to reduce java A cross function global data flow analysis algorithm for synchronous load and memory heap allocation pressure in the program .
· Through escape analysis ,java Hotspot The compiler can analyze the usage scope of a new object's reference to determine whether to allocate the object to the heap .

· The basic behavior of escape analysis is to analyze the dynamic scope of objects :
> When an object is defined in a method , Objects are used only within methods , Blame that there was no escape .
> When an object is defined in a method , He was quoted by external methods , It is thought that escape happened .
 For example, passing it as a call parameter to other places 

Conclusion : Local variables can be used in development , Don't define it outside the method .

12、 Escape analysis : Code optimization

 Using escape analysis , The compiler can optimize the code as follows :
> On the stack .
 Convert heap allocation to stack allocation .
> Synchronous ellipsis .
 If an object is found to be accessible only from one thread , So the operation of this object can not consider synchronization 
> Detach object or scalar substitution 
 Some objects may not need to exist as a continuous memory structure or can be accessed , Then part or all of the object can be left out of memory , It's stored in CPU In the register 

Two 、 Method area

1、 Stack 、 Pile up 、 Method area interaction

2、 An overview of the method area

· The method area also has an alias called Non-Heap( Non heap ), Although all method areas are logically part of the heap .
 So the method area can be seen as a block independent of java Heap memory space .

· Method area (Method Area) And java Pile up , Is an area of memory Shared by each thread .

· Methods in JVM Created at startup , And his actual indoor memory space is as discontinuous as the heap area 
· The method area is the same size as the heap space , You can choose to be fixed size or scalable 

· The size of the method area determines how many classes the system can hold , If the system defines too many classes , Cause method area overflow .
 Virtual machines also throw out memory overflow errors :java.lang.OutOfMemoryError:PermGen space or 
 person java.lang.OutOfMemoryError:Metaspace

· close JVM This will free the memory in this area 
## Method area evolution 

Java7 And before , It is customary to call the method area permanent generation .
Java8 Start , Use meta space instead of permanent generation 
【Java8 in the future , It is a method area implemented in meta space ; stay Java8 Before , It is a method area implemented by permanent generation 】

【 Meta space uses   Local memory    Not JVM Memory 】
【 The original permanent use is JVM Of memory , Now the Metaspace uses   Local memory 】

3、 Set the method area size with OOM

##Java7 And before :
-XX:PermSize  Set permanent generation initial allocation space . Default 20.75m
-XX:MaxPermSize  Set permanent generation maximum allocable space  32 The bit computer defaults to 64M,64 The bit computer defaults to 82M
 When JVM If the class information capacity exceeds this value, it will be reported OutOfMemoryError:PermGen Space
【-XX:PermSize=100m  -XX:MaxPermSize=500M】


##Java8 And after :
-XX:MetaspaceSize  Set the initial allocation space of meta space   Default 21M
-XX:MaxMetaspaceSize  Set the maximum allocable space of meta space   Default -1, There is no limit to 
 When JVM If the class information capacity exceeds this value, it will be reported OutOfMemoryError:Metaspace Space
【-XX:MetaspaceSize=100m  -XX:MaxMetaspaceSize=500M】


 Default -XX:MetaspaceSize by 21MB, This is the initial high water mark , Once you touch this water line ,
Full GC Will trigger and unload useless classes ( That is, the class loader corresponding to this class is no longer alive ), And then this high water 
 The bit line will reset . The value of the new high water mark depends on GC How much meta space has been released after . If you don't have enough free space , that 
 No more than MaxMetaspaceSize when , Increase the value properly 、 If you release too much space , Then lower the value appropriately 


 If the initial high water mark is set too low , The above high water mark adjustment will happen many times . Days through the garbage collection period 
 Zhi can observe Full GC Multiple calls . To avoid frequent GC, Minus one will XX:MetaspaceSize Set to 
 A relatively high value 

How to solve OOM

1、 To solve OOM Abnormal or heap space abnormal , The general method is to first analyze the tool heap through memory mapping dump
 Analysis of the heap dump snapshot , The point is to make sure that objects in memory are necessary , That is to say, we should first distinguish between them 
 It's a memory leak (Memory Leak) Or memory overflow (Memory Overflow)

2、 If memory leaks (Memory Leak), You can further view the leaked object to GC Roots References to 
 chain . Then we can find out the path and GC Roots Associate and cause the garbage collector to fail to automatically 
 Recycle their . Master the type information of the leaking object , as well as GC Roots Reference chain information , It can be more accurate 
 Locate the leak code .

3、 If there is no memory leak , In other words, objects in memory must still exist , Then we should check for falsehood 
 The parameters of the simulated reactor (-Xmx And -Xms), Compare with the memory in the machine room to see if it can be increased , From the code check is 
 Whether some objects have a long life cycle 、 Long holding time , Try to reduce memory consumption during program running .

4、 The internal structure of the method area

· The contents of the method area :
> Type information ( Domain information 、 Methods information )、 Constant 、 Static variables 、 Even if the compiler compiles the code cache and so on 

## One 、 Type information 
 Heap the type of each load ( class class\ Interface interface\ enumeration Enum\ annotation annotation),JVM You have to store the type information in the method area :
> The full valid name of this type ( full name = Package name . Class name )
> The fully valid name of the direct parent of this type 
> This type of modifier (public abstract final Some subset of )
> This type of direct interface has a sequence table 

## Two 、 Domain Field Information ( Member variables )
JVM All domain related information of the type and the order in which the fields are declared must be kept in the method area 
> Domain related information includes : Domain name city 、 Domain type 、 Domain modifier (public private protected static final volatile transient Some subset of )

## 3、 ... and 、 Methods information 
JVM The following information must be saved for all methods , As with domain information, it includes the order of declaration :
> Method name 
> Return type of method ( or void)
> Number and type of method parameters ( According to the order )
> Method modifier (public private protected static final synchronized abstract native A subset of )
> Bytecode of method 、 The stack of operands 、 Local variable table and size 
> Anomaly table ( Where each exception begins 、 End 、 The code deals with the offset address in the program counter 、 Constant pool index of the caught exception class )


·non-final Class variables 
> Static variables are associated with classes , Load as class loads , They become a logical part of class data 
> Class variables are shared by all instances of a class , Even if there is no class instance, you can access 
> Global constants :static final, Be declared final Class variables are treated differently , Each global constant is assigned at compile time .

## Four 、 Runtime constant pool  VS  Constant pool 
· Method area : The interior contains   Runtime constant pool runtime constant pool
· Bytecode file : The interior contains   Constant pool constant pool
[ notes : Constant pool in bytecode file , When it is loaded into the method area, it is called the runtime constant pool ]

 Constant pool table Constant Pool Table, It includes all kinds of   Literal   And to type 、 Domain and method " Symbol reference ".

· Why constant pools are needed ?
 One java Classes in the source file 、 Interface , After compiling, a bytecode file is generated . and java Bytes in 
 Data code support is required , Usually this data is too large to be stored directly in bytecode , For another 
 The way , It can be stored in a constant pool , This bytecode contains a reference to the constant pool . When dynamically linking 
 The runtime constant pool will be used later .
 Such as :
public class SimpleClass{
  public void sayHello(){
   System.out.println("hello");
  }
}
 Although the above code is very small , But it uses String\System\PrintSream And 
Object Isostructure . The amount of code here is actually very small , If there's a lot of code , The referenced structure will 
 more ! Here we need constant pools !
( We are class In bytecode files , It won't introduce string、system、printstream、Object The source file of , Just introduce its reference --> Symbol reference )


· What's in the constant pool ?
 The data types stored in the constant pool include : Quantity is worth 、 A string value 、 Class reference 、 Field reference 、 Method reference 


 A constant pool can be seen as a table , The virtual machine instruction finds the class name to execute according to this constant table 、 Method name 、 Parameter type 、 Literal quantity, etc .


· Runtime constant pool 
> The runtime constant pool is part of the method area 
> The constant pool is class Part of the document , Used to store various literal quantities and symbol references generated by the compiler 
 use , This part will be stored in the runtime constant pool of the method area after the class is loaded 
> Runtime constant pool , After loading classes and interfaces to the virtual machine , The corresponding runtime constant pool will be created 
>JVM For each loaded type ( Class or interface ) Both maintain a constant pool . The data in the pool is like numbers 
 The group is the same , It's accessed by index 
> The runtime constant pool contains many different constants , Including the numeric literal defined by the compiler ,
 It also includes method or field references that are not available until runtime resolution , This is no longer a constant pool symbol 
 Address , Here's the real address .
> The runtime constant pool is similar to the symbol table in traditional programming languages , But it contains more data than symbols 
 The watch is more abundant 
> When creating a pool of runtime constants for a class or interface , If the paparazzi runtime constant pool requires more memory space than 
 Beyond the maximum value that the method area can provide , be JVM Will throw out OutOfMemoryError abnormal 

example :

public class MethodArea {

    public static void main(String[] args) {
        int x=500;
        int y=100;
        int a=x/y;
        int b=50;
        System.out.println(a+b);
    }

}

Compiled file

Classfile /D:/WorkSpace/DailyCodePackage/basic/target/classes/com/lee/jvm/rundataarea/MethodArea.class
  Last modified 2020-12-7; size 670 bytes
  MD5 checksum 42390faabe2fc63519914b0ac436af5f
  Compiled from "MethodArea.java"
public class com.lee.jvm.rundataarea.MethodArea
  minor version: 0
  major version: 52
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
   #1 = Methodref          #5.#25         // java/lang/Object."<init>":()V
   #2 = Fieldref           #26.#27        // java/lang/System.out:Ljava/io/PrintStream;
   #3 = Methodref          #28.#29        // java/io/PrintStream.println:(I)V
   #4 = Class              #30            // com/lee/jvm/rundataarea/MethodArea
   #5 = Class              #31            // java/lang/Object
   #6 = Utf8               <init>
   #7 = Utf8               ()V
   #8 = Utf8               Code
   #9 = Utf8               LineNumberTable
  #10 = Utf8               LocalVariableTable
  #11 = Utf8               this
  #12 = Utf8               Lcom/lee/jvm/rundataarea/MethodArea;
  #13 = Utf8               main
  #14 = Utf8               ([Ljava/lang/String;)V
  #15 = Utf8               args
  #16 = Utf8               [Ljava/lang/String;
  #17 = Utf8               x
  #18 = Utf8               I
  #19 = Utf8               y
  #20 = Utf8               a
  #21 = Utf8               b
  #22 = Utf8               MethodParameters
  #23 = Utf8               SourceFile
  #24 = Utf8               MethodArea.java
  #25 = NameAndType        #6:#7          // "<init>":()V
  #26 = Class              #32            // java/lang/System
  #27 = NameAndType        #33:#34        // out:Ljava/io/PrintStream;
  #28 = Class              #35            // java/io/PrintStream
  #29 = NameAndType        #36:#37        // println:(I)V
  #30 = Utf8               com/lee/jvm/rundataarea/MethodArea
  #31 = Utf8               java/lang/Object
  #32 = Utf8               java/lang/System
  #33 = Utf8               out
  #34 = Utf8               Ljava/io/PrintStream;
  #35 = Utf8               java/io/PrintStream
  #36 = Utf8               println
  #37 = Utf8               (I)V
{
  public com.lee.jvm.rundataarea.MethodArea();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=1, locals=1, args_size=1
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object."<init>":()V
         4: return
      LineNumberTable:
        line 3: 0
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            0       5     0  this   Lcom/lee/jvm/rundataarea/MethodArea;

  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=3, locals=5, args_size=1
         0: sipush        500
         3: istore_1
         4: bipush        100
         6: istore_2
         7: iload_1
         8: iload_2
         9: idiv
        10: istore_3
        11: bipush        50
        13: istore        4
        15: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
        18: iload_3
        19: iload         4
        21: iadd
        22: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
        25: return
      LineNumberTable:
        line 6: 0
        line 7: 4
        line 8: 7
        line 9: 11
        line 10: 15
        line 11: 25
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            0      26     0  args   [Ljava/lang/String;
            4      22     1     x   I
            7      19     2     y   I
           11      15     3     a   I
           15      11     4     b   I
    MethodParameters:
      Name                           Flags
      args
}
SourceFile: "MethodArea.java"

5、 The evolution of method areas

edition change
jdk1.6 And before There is a permanent generation , Static variables are stored in the permanent generation
jdk1.7 There is a permanent generation , But the string constant pool 、 Static variable removal , Keep it in the pile
jdk1.8 And after There is no permanent generation , Type information 、 Field 、 Method 、 Constants are stored in the meta space of local memory , But string constant pool 、 Static variables are still on the heap

## Why are permanent generations replaced by meta spaces 
· It's hard to determine the size of the permanent generation space 
 In some cases , If there are too many classes loaded dynamically , Easy to produce Perm Of OOM. The biggest difference between Metaspace and permanent generation is : The meta space is not in the virtual machine , It's using local memory . therefore , By default , The size of the meta space is limited only by local memory 

· Tuning permanent generations is difficult 
Full GC Long time , Make a long time STW, Affect the efficiency of the program 


##StringTable Why adjust 
JDK7 take StringTable The string constant pool is in the heap , Because the recycling efficiency of permanent generation is very low , stay 
Full GC It will trigger . and Full GC It's the lack of space in the old days 、 Only when there is a permanent shortage of generation can we touch 
 Hair . And that leads to this StringTable The recovery efficiency is not high . And there will be a lot of strings created in our development 
 build , Recycling efficiency is low , Causes the permanent generation to run out of memory . Put it in the pile , Can even recycle memory .

6、 Garbage collection in method area

 Method area GC It mainly includes two parts : Discarded constants in constant pool   and   Types that are no longer used 

3、 ... and 、 Run time data area summary

 Consider the following :
## One 、 The way JVM Memory model , What areas are there , What to do separately ?

## Two 、JAVA8 Memory generation improvement ?

## 3、 ... and 、 The difference between stack and heap ? The structure of the pile ? Why two survivor District ?

## Four 、Eden and Survivor The distribution proportion of ?

## 5、 ... and 、JVM Memory partition , Why should we divide the new generation 、 Old age and enduring generation ?

## 6、 ... and 、 When will the object enter the old age ?

## 7、 ... and 、JVM Will garbage collection happen in permanent generation ?

Four 、 Object instantiation memory layout and access location

Object instantiation :

1、 How to create objects :
>new
>Class Of newInstance
>Constructor Of newInstance(xxx)
> Use clone()
> Using deserialization 
> Third party Library Objenesis


2、 To create an object :
> Determine whether the class corresponding to the object is loaded 、 link 、 initialization 
 Virtual opportunity to a new Instructions , First of all, check whether the parameters of this instruction are in metaspace In the constant pool of 
 A symbolic reference to a class , Also check whether the class represented by the symbol reference has been loaded 、 Parse and initialize .
 without , So in the parental delegation mode , Use the current classloader to classLoader+ Package name + Class called 
key Search for the corresponding .class file . If no files are found , Throw out 
classNotFoundException abnormal , If you find , Then load the class , And generate the corresponding Class class 
 object .


> Allocate memory for objects 
 First, calculate the size of the space occupied by the object , Then divide a block of memory in the heap for the new object . If the instance member variable is a reference variable , Just allocate reference variable space (4 Byte size )


> Dealing with concurrency security issues 
 use CAS Failure to retry 、 Region locking guarantees the atomicity of updates 
 Each thread is pre allocated a block TLAB


> Initialize the space allocated to 
 All properties set default values , Ensure that the object instance field can be used directly without assignment 


> Set the object header of the object 
 The class that the object belongs to 、 Object's HashCode And objects GC Information 、 Data such as lock information is stored in the object header of the object . How this process is set depends on JVM Realization 


> perform init Method to initialize 
 Initialize member variables , Execute instantiation code block , Call the constructor of the class , The first address of the object in the heap is assigned to the reference variable .

Memory layout of objects :

1、 Object head Header
> Runtime metadata 
 Hash value 、GC Generational age 、 Lock status flag 、 A lock held by a thread 、 To the thread ID、 Bias timestamp 
> Point to class metadata InstanceKlass, Determine the type the object belongs to 
 That is, it points to the specific type of the object in the meta space or method area 
( notes : If it's an array , Also record the length of the array )


2、 The instance data Instance data
 It's the valid information that the object really stores , Includes various types of fields defined in program code ( This includes the integration from the parent class and its own )

3、 Alignment filling 
 It's not necessary 

Object access location :

 There are two main ways to access objects :
> Handle access ( Waste space and inefficiency )
 In the stack frame refrence The handle pool pointing to the corresponding heap space , The handle pool consists of two parts , One is to the object 
 The pointer to the instance data of the object in the heap , The other is the pair that points to the method area of the object type data 
 Like type data 

> Direct Pointers (HotSpot Adopted )( Save space, fast )
 In the stack frame refrence Instance data that points directly to the object , The data type from the object to the instance 
 Point to the object type data in the method area 
 Consider the following :
## One 、 The object is JVM How is it stored in ?

## Two 、 What's in the object header ?

## 3、 ... and 、JVM If you access the object instance inside the stack frame through the object reference in the stack frame ?

版权声明
本文为[There is a Fei]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201207174810368h.html