当前位置:网站首页>How much do you know about JVM memory management
How much do you know about JVM memory management
2022-07-28 13:17:00 【daydreamed】
JVM memory management How much do you know
1、 summary
“Java Virtual machine is executing Java In the process of the program, the memory it manages will be divided into several different data areas . These areas have their own uses , And when it was created and destroyed , Some regions exist with the start of virtual machine process , Some areas are created and destroyed depending on the start and end of the user thread .”
Java The data area when the virtual machine is running :
Add :
Thread isolated data area :
- Virtual machine stack (VM Stack)
- Native Method Stack (Native Method Stack)
- Program counter (Program Counter Register)
Data area shared by threads :
- Method area (Method Area)
- Pile up (Heap)
2、Java Memory area
Program counter (Program Counter Register)
Program counter yes For storing the next one (Java virtual machine ) Address of the unit where the bytecode instruction is located The place of , Memory of this area Belong to “ Thread private ” Memory .
If Threads What is being implemented is a Java Method , The value of this counter is executing (Java virtual machine ) The address of a bytecode instruction ; If Threads What is being executed is local (Native) Method , Then the value of this counter is null .
Virtual machine stack (VM Stack)
Virtual machine stack yes To hold Stack frame (Stack Frame) The place of , Whenever a (Java) When the method is executed ,Java virtual machine It creates a Stack frame , Stack frame It stores Local variable table 、 The stack of operands 、 Dynamic connection 、 Method exit information , One (Java) Method from call To completion of enforcement The process of Corresponding Stack frame Push To Out of the stack The process of , Memory of this area Belong to “ Thread private ” Memory .
Native Method Stack (Native Method Stack)
Native Method Stack With the function of Virtual machine stack be similar , The only difference is Virtual machine stack In the service of Virtual machine execution Java Method , Native Method Stack In the service of The virtual machine executes local methods , Memory of this area Belong to “ Thread private ” Memory .
Pile up (Heap)
Pile up yes To hold (Java) Object instances The place of , Memory of this area Belong to “ Thread sharing ” Memory .
Pile up yes Garbage collector Managed memory area , So it's also called “GC Pile up ”.
The size of the heap Can pass (Java virtual machine ) Parameters -Xmx and -Xms To set .
Method area (Method Area)
Method area It's for storing Type information loaded by the virtual machine 、 Constant 、 Static variables 、 Real time compiler compiled code cache and other data The place of , The memory of this area Belong to “ Thread sharing ” Memory .
Expand :
Runtime constant pool (Runtime Constant Pool)
Runtime constant pool yes Method area Part of , To hold Various generated during compilation Literal And Symbol reference .
Direct memory (Direct Memory)
Direct memory Does not belong to Java Memory area , But this part of memory is also used frequently , for example : adopt Native The function library directly allocates Out of heap memory , Reduce data transmission loss , Improve performance .
Direct memory Only limited by local memory .
3、Java object
3.1、 Object creation
stay Java In language , Creating an object requires only one keyword new , But in Java virtual machine in , To create an object, you need to go through the following steps .
1、 When Java virtual machine Encountered a bytecode new When the command , First of all, I'll check The parameters of this instruction Is it possible to be in Constant pool To A symbolic reference to a class , And check this The class represented by the symbolic reference whether Has been loaded 、 Parsed and initialized , If not, execute first Class loading process of this class .
2、 After the class load check passes , virtual machine adopt “ Pointer collision ”( or “ Free list ”) Distribution method stay Pile up In Chinese, it means This object allocates memory space .
3、 After memory space allocation , virtual machine Must be Allocated memory space ( But it doesn't include the object head ) All initialized to Zero value .
4、 Next , virtual machine It will also help object Make the necessary Settings , Such as : The object is an instance of which class 、 How can I find the metadata information for a class 、 Object's hash code ( Postpone to Object:hashCode() Call to And then we do the calculation )、 Object's GC Generational age, etc , This information is stored in In the object header of the object .
5、 thus , From a virtual machine perspective , A new object has been born , But from Java From a procedural point of view , Object creation just started ( The constructor has not been executed yet ), Next is Execute constructor ( In the virtual machine, it is <init>() Method ) Finish right Object initialization , To complete formally Object construction .
3.2、 Memory layout of objects
object stay Pile up The memory layout in can be divided into three parts :
- Object head (Header)
- The running data of the object itself : Hash code 、GC Generational age 、 Lock status flag, etc
- Type a pointer : Point to Object type metadata ( namely Is an instance of which class )
- The instance data (Instance Data)
- Field contents
- Add to it (Padding)
- Place holder
3.3、 Object access location
Java When programs use objects , Will pass Stack Upper reference Data to operate Pile up Specific objects in , and reference( quote ) Access location Pile up Objects in can be divided into two ways :
Handle access
Pile up Partition a piece of memory as a handle pool ( Handle contains Object instance data address And Type data address ),reference What's stored in is Object's handle address .
advantage :reference A stable handle address is stored in , Only the instance data pointer in the handle will be changed when the object is moved .

Direct pointer access
reference Store directly in Object address .

advantage : Compared with the handle mode Save the time cost of a pointer location , Improved access speed .
3.4、 References to objects
Strong citation (Strongly Reference)
finger Reference assignment in program code (
Object obj = new Object()), as long as Strong reference relationship There is still , Garbage collector Will never be recycled The object of reference .Soft citation (Soft Reference)
finger Some of them are useful 、 But not necessarily , Will happen in the system Memory overflow exception front , Garbage collector These objects will be recycled .
JDK1.2 after , Provide SoftReference class Realization Soft citation .
Weak reference (Weak Reference)
finger Some non essential objects , When Garbage collector When starting work , Whether the current memory is sufficient or not , These objects will be recycled .
JDK1.2 after , Provide WeakReference class Realization Weak reference .
Virtual reference (Phantom Reference, also called “ Ghost quotes ” or “ Phantom reference ”)
Whether an object has a virtual reference , It doesn't affect their survival time at all , Nor can virtual references be used to get an object instance , The only purpose of its existence is : In order to be able to be Garbage collector Receive a system notification when recycling .
JDK1.2 after , Provide PhantomReference class Realization Virtual reference .
3.5、 The survival of objects
Be an object “ Death ” when ,GC(Garbage Collection, garbage collection ) The object will be cleared and Reclaim the memory space allocated to the object . that ,GC How to judge whether an object is “ Death ” What about it ?
GC Determine whether an object is “ Death ” There are usually two algorithms :
Reference counting algorithm
stay object Add a Reference counter , Whenever there's a place to quote it , Counter value plus one ; Whenever a reference to a place fails , The counter value minus one ; The counter value at any time is zero The object of is “ Dead ” The object of ( namely This object can no longer be used ).
- advantage : The principle of simple , High judgment efficiency
- shortcoming : Take up extra memory space 、 Cannot solve the problem of circular reference between objects
Reachability analysis algorithm
With “GC Roots”( Root object ) As the starting node set , Start with these nodes , Search down... Based on reference relationships , The path taken by the search process is called “ References to the chain (Reference Chain)”, If An object To “GC Roots” There is no References to the chain Connected to a ( perhaps In the words of graph theory, it is from “GC Roots” To This object is unreachable ) when , This object “ Dead ”( namely This object can no longer be used ).
- advantage : It solves the problem of circular reference between objects
- shortcoming : Compare with Reference counting algorithm Judge efficiency It's not that high
Expand :Java Medium “GC Roots”
- Virtual machine stack ( Local variables in stack frames ) in Referenced object , Such as : Currently running method Used in Parameters 、 local variable 、 Temporary variables, etc
- Method area Class static properties Referenced object , Such as :Java class Reference type static variable of
- Method area Constant Referenced object , Such as : The string reference in the pool
- Local method stack JNI(Native Method ) Referenced object
- Java virtual machine Internal references , Such as : Basic data type object Class object 、 Some resident exception objects (NullPointException、OutOfMemoryError)、 system class loader
- All are locked in sync (synchronized keyword ) The object of holding
- reflect Java virtual machine The internal situation JMXBean、JVMTI Callback registered in 、 Local code cache, etc
- Different garbage collectors and Different reclaimed memory areas Medium “ Temporary ” object

Add :
- Object's “ Probation ”:
When an object is in Reachability analysis algorithm It is determined as When an object is unreachable , The object will enter “ Probation ” Stage : Detect whether it is necessary for the object to execute finalize() Method .
If the object is not overridden finalize() Method ( or finalize() Method has been called by the virtual machine ), be virtual machine Think that the object It's not necessary finalize() Method , Really announce its “ Death ”;
otherwise , virtual machine Think that the object It is necessary to carry out finalize() Method , And put the object into F-Queue In line , Then the virtual machine Automatically created 、 Low scheduling priority Of Finalizer Threads To carry out its finalize() Method ( there “ perform ” The virtual opportunity triggers the method to run , But it doesn't promise to wait for it to run out ).
- Object's “ be reborn ”:
When the object is finalize() In the method Re associate with any object on the reference chain , Such as : Put yourself (this keyword ) Assign to a class variable or a member variable of an object , namely This object gets “ be reborn ”( Removed from the “ About to be recycled ” Set ).
contrary , If the object is in finalize() In the method Failed to re associate with any object on the reference chain , The object will also face “ Death ”.
4、 Garbage collection algorithm
4.1、 Generational collection theory
Generational collection is called theory , In essence, it's a set of rules of thumb that fit the actual situation of most programs , It is based on two generational hypotheses and a rule of thumb .
Weak generational Hypothesis (Weak Generational Hypothesis): The vast majority of objects are born and perished
Strong generational Hypothesis (Strong Generational Hypothesis): The more times you go through the garbage collection process, the more difficult it is for an object to die
Cross generational citation Hypothesis (Intergenerational Reference Hypothesis): Cross generation references account for only a very small number of references compared to the same generation references
be based on Generational collection theory , Garbage collector The consistent design principle is : The collector should put Java Pile up different areas , Then the objects will be recycled according to their age ( The number of times an object has survived the garbage collection process ) Allocated to different areas to store .
Add :
Java Generation of the heap
- The new generation (Young Generation)
- Old age (Old Generation)
Generational collection
- Part of the collection (Partial GC):
- Cenozoic collection (Minor GC / Young GC): Only garbage collection for the new generation
- Old age collection (Major GC / Old GC): Garbage collection for the elderly only
- Mixed collection (Mixed GC): Yes Garbage collection is carried out throughout the Cenozoic , Also on the Garbage collection is carried out in some old times
- Collect the whole pile (Full GC): To the whole Java Pile up and Method area Garbage collection
4.2、 Mark - Clear algorithm
The algorithm is divided into “ Mark ” and “ eliminate ” Two phases : First mark all objects to be recycled , After the tag is done , Recycle all marked objects in a unified way ( Or uniformly recycle all unmarked objects ).
shortcoming : Creating debris space .

4.3、 Mark - Copy algorithm
Divide memory into two equal sized blocks according to capacity , Use only one piece at a time , When this block of memory runs out , Copy the existing object to another piece , Then clean up the used memory space at one time .
shortcoming : Halve available memory .

4.4、 Mark - Sorting algorithm
Marking process of Algorithm And “ Mark - Clear algorithm ” Agreement , The sorting process is : Move all living objects to one end of memory space , Then clean up the memory outside the boundary .
shortcoming : Move Big object It may cause a long pause .

All the above contents are from the right Teacher zhou zhiming's 《 In depth understanding of Java virtual machine 》 Summary of some contents of .
My summary is compared with the content of this book , Nothing is equal to the water drop and the river , I sincerely recommend you to read this book carefully .
The above content is only for personal learning .
边栏推荐
- 黑猫带你学eMMC协议第24篇:eMMC的总线测试程序详解(CMD19 & CMD14)
- QT signal and slot mechanism (detailed)
- Android工程师,如何使用Kotlin提供生产力?
- [matlab] IIR filter
- Unity—“合成大西瓜”小游戏笔记
- 【嵌入式C基础】第7篇:C语言流程控制详讲
- 【嵌入式C基础】第6篇:超详细的常用的输入输出函数讲解
- Xampp Chinese tutorial guide
- Use and source code of livedata in jetpack family bucket
- What if the win11 folder cannot be opened
猜你喜欢

Brother bird talks about cloud native security best practices

How can non-standard automation equipment enterprises do well in product quality management with the help of ERP system?

【嵌入式C基础】第6篇:超详细的常用的输入输出函数讲解

我抄底了被清算的NFT,却被OpenSea上了锁

Chinese translation of pointnet:deep learning on point sets for 3D classification and segmentation

Connected Block & food chain - (summary of parallel search set)

How does kotlin help you avoid memory leaks?

Machine learning Basics - integrated learning-13
![[Bi design teaching] STM32 and FreeRTOS realize low power consumption](/img/2b/3af85135e08599aaa425698c0e83aa.png)
[Bi design teaching] STM32 and FreeRTOS realize low power consumption

Fundamentals of machine learning Bayesian analysis-14
随机推荐
RGB game atmosphere light touch chip-dlt8s04a-jericho
企业数字化本质
Android engineers, how to use kotlin to provide productivity?
[embedded C foundation] Part 6: super detailed explanation of common input and output functions
Summary: golang's ide:vscode usage
[embedded explanation] key scanning based on finite state machine and stm32
Change password, confirm password verification antd
[June 28 event preview] low code Summit
【嵌入式C基础】第5篇:原码/反码/补码
Use and source code of livedata in jetpack family bucket
LeetCode·每日一题·1331.数组序号转换·离散化
拥有游戏的一部分,写在我的世界禁用NFT之后
With 433 remote control UV lamp touch chip-dlt8sa20a-jericho
[embedded C foundation] Part 7: detailed introduction to C language process control
Black cat takes you to learn EMMC protocol chapter 27: what is EMMC's dynamic capacity?
[embedded C foundation] Part 1: basic data types
The form select in antd is received before it is selected
What if win11 cannot recognize Ethernet
【嵌入式C基础】第6篇:超详细的常用的输入输出函数讲解
How does kotlin help you avoid memory leaks?