当前位置:网站首页>Detailed explanation of JVM memory layout (glory collection version)
Detailed explanation of JVM memory layout (glory collection version)
2022-07-28 21:47:00 【Dragon back ride Shi】

Catalog
3、JVM Stacks Virtual machine stack
4、Native Method Stacks( Native Method Stack )
5、Program Counter Register ( Program count register )
One 、 Memory layout
JVM The memory layout defines Java Memory request during run 、 Distribute 、 Managed policies , To ensure the JVM Stable and efficient operation of . Different JVM There are some differences in memory partition and management mechanism . combination JVM Virtual machine specification , Come together and discuss jVM Memory layout . As shown in the figure below :
1、Heap Heap area
Heap The heap area is Java happen OOM(Out Of Memory) Fault location , The heap stores what we usually create Instance object , Eventually, these objects that are no longer used will be recycled by the garbage collector , and The heap is thread shared . In general , The memory space occupied by the heap is JVM The largest in the memory area , In our usual coding , Create objects without restraint , Memory space will also be exhausted .
The memory space of the heap can Custom size Of , Also support in Dynamic modification at run time , adopt -Xms 、-Xmx These two parameters change the heap Initial value and Maximum .-X refer to JVM Operation parameters ,ms yes memory start For short , It stands for Minimum heap capacity ,mx yes memory max For short , It stands for Maximum reactor capacity ; Such as -Xms256M The initial value representing the heap is 256M,-Xmx1024M The maximum value representing the heap is 1024M.
Because the memory space of the heap can be adjusted dynamically , So when the server is running , The uncertainty of request traffic may cause the memory space of our heap to constantly adjust , It will increase the pressure on the server , So we usually JVM Of Xms and Xmx Set the value of to the same , Also to avoid GC( Garbage collection ) Then adjust the extra pressure brought by the heap. .
The heap is divided into two regions :Young Area and Old District , also called The new generation and Old age . When the object was first created , Will be created in The new generation , At a certain stage, it will be transferred to the old age , If you create a new object that the new generation cannot accommodate , Then this new object can also be created to the old age . As shown in the figure above .
The new generation It is divided into 1 individual Eden Area and 2 individual S District ,S representative Survivor. Most objects will be in Eden District In the middle of , When Eden When the workspace does not have enough space to accommodate new objects , Will trigger Young Garbage Collection, namely YGC. stay Eden When garbage is removed from the area , Its strategy is to Objects that are not referenced are directly recycled , And the referenced objects will be transferred to Survivor District .
Survivor There are S0 and S1 Two memory spaces , Every time YGC When , The surviving objects are copied to the unused memory space , Then completely clear the space currently in use , Then exchange the usage of the two spaces . If YGC The object to be transferred Survivor The area can't hold , Then the object will be handed over directly to the elderly generation .
It says , To Certain stage The object will be transferred to the elderly area , What does that mean ? Every object has a counter , When every time YGC When , Metropolis +1. adopt -XX:MAXTenuringThrehold Parameter can be configured when the value of the counter reaches a certain threshold , The object will be transferred from the new generation to the old age .
The default value for this parameter is 15, in other words The object is Survivor In the district S0 and S1 The number of memory space exchanges is accumulated 15 After that , Will be transferred to the old age . If the parameter is configured to 1, Then the created objects will be transferred directly to the old age . The specific object allocation, i.e. recycling process, can be seen as shown in the figure below .
If Survivor I can't put it down , Or create a very large new object ,Eden and Old No storage area , It will trigger Full Garbage Collection, namely FGG, Then try to put it again Old District , If you still can't hold it , Will throw OOM abnormal . In different JVM Implementation and different recycling mechanisms , Heap memory is divided differently .
2、Metaspace Meta space
stay JDK8 In the version , The predecessor of Metaspace Pern The district has been eliminated . stay JDK7 And previous versions ,Hotspot also Pern District , Permanent generation , The size has been determined at startup , Difficult to tune , And only FGC Will move the class meta information . Different from previous versions Pern( Forever ),JDK8 Of Meta space Already in Local memory Middle distribution , also ,Pern All content in the area String constant Moved to Heap memory , Other contents are also included Class meta information 、 Field 、 Static attribute 、 Method 、 Constant Wait, move to Meta space Inside .
3、JVM Stacks Virtual machine stack
Stack (Stack) It's a First in, then out Data structure of , How do you understand first in and then out ? Similar to when we usually play badminton , Badminton tube , The first one put in is often the last one , The last one put in comes out first .
Compared to the register based operating environment ,JVM Is based on The stack structure Operating environment . Because the stack structure is more portable , More controllable .JVM The virtual machine stack is described Java Memory area of method execution , And is Thread private Of . The elements in the stack are used to support the virtual machine to make method calls , The process from the beginning of each method call to the completion of execution , This is the process of stack frame from input frame to output frame .
In the active thread , Only the frame at the top of the stack is valid , be called Current stack frame . The method being implemented is called The current method , Stack frame is the basic structure of method operation . At execution engine run time , All instructions can only operate on the current stack frame . and StackOverflowError Indicates stack overflow of request , Cause memory to run out , Usually in recursive methods . If you put JVM As a chessboard , Virtual machine stack Is the general on the chessboard / handsome , Stack frame of current method Is the area where the pieces can go , and Stack operation Is every piece . The stack pressing and stack out of the operation stack are shown in the figure below :
Virtual machine stack through Pressing stack and Out of the stack The way , The active stack frame corresponding to each method is processed , The normal execution of the method ends , It will jump to another stack frame . In the process of execution , If there is an anomaly , There will be abnormal backtracking , The return address is determined by the exception handling table . Stack frame in the whole JVM The position in the system is quite high , Include Local variable table 、 Stack operation 、 Dynamic connection 、 Method return address etc. .
The following is a brief analysis of each active stack frame of the stack frame
(1) Local variable table
The local variable table is used to store Method parameter and local variable Region . We all know , Class attribute variables go through two stages , It is divided into Preparation stage and Initialization phase , Local variables are not in the preparation stage , Only Initialization phase , And it has to be Show Of . If it's a nonstatic method , It's in index[0] What is stored on the location is Instance reference of the object to which the method belongs , Then stored is Parameters and local variable . In the bytecode instruction STORE Instruction is Write the calculated local variables in the operation stack back to the storage space of the local variable table .
(2) Stack operation
The operation stack is a Bucket stack with empty initial state . During method execution , There are various instructions to write and extract information from the stack .JVM The execution engine of is based on stack , The stack refers to Stack operation . Bytecode instruction sets are defined as Based on stack type Of , The depth of the stack is in the method meta information stack Properties of the , The following is an example to illustrate the interaction between the operation stack and the local variable table :
public int add() {
int x = 10;
int y = 20;
int z = x + y;
return z;
}
The bytecode operation sequence is as follows :
public int add();
Code:
0: bipush 10 // Constant 10 Push into the operation stack
2: istore_1 // And saved to the local variable table slot_1 in ( The first 1 It's about )
3: bipush 20 // Constant 20 Push into the operation stack
5: istore_2 // And saved to the local variable table slot_2 in
6: iload_1 // Put the local variable table slot_1 Elements (int x) Push into the operation stack
7: iload_2 // Put the local variable table slot_2 Elements (int y) Push into the operation stack
8: iadd // Take both numbers from the top , stay CPU Riga , And press back to the top of the operation stack
9: istore_3 // Store the results at the top of the stack in the local variable table slot_3 in
10: iload_3
11: ireturn // Returns the value of the top element of the stack
The first 1 Description : The local variable table is like an express cabinet , There are many cabinets , The serial number is 1,2,3,...,n, Bytecode instruction istore_1 It means open 1 Cabinet No , Then put the value at the top of the stack 10 Put into . The stack is like a bucket , You can only operate on the elements of the can mouth at any time , So data can only be accessed at the top of the stack . Some instructions can be carried out directly in the cabinet , such as iinc Instructions , Directly to the value in the drawer +1 operation . We often come across i++ and ++i, By bytecode comparison , The answer is clear at a glance . As shown in the table below :

Zuo liezhong ,iload_1 From the 1 Take out a number from cabinet No , Press into the top of the stack , The next step is directly implemented in the cabinet + 1 The operation of , This operation has no effect on the value of the top element of the stack , therefore istore_2 Just assign the top element of the stack to a, And the right column , It is first carried out in the cabinet +1 The operation of , And then through iload_1 The first 1 The number in cabinet No. 1 is pressed into the top of the stack , therefore istore_2 Assign to a The value of is +1 The value after . Under expansion ,i++ Not atomic . Even if passed volatile Keyword to decorate , multithreading , There will still be data coverage .
(3) Dynamic connection
Each stack frame contains a A reference to the current method in the constant pool , The purpose is Support dynamic connection of method calling procedure .
(4) Method return address
There are two exit situations during method execution : First of all , The normal exit , namely Normal execution of return bytecode instructions to any method , Such as RETURN、IRETURN、ARETURN etc. ; second , Abnormal exit . No matter what exit situation , Will return the location where the method is currently called . Method exit is equivalent to pop up the current stack frame , There may be three ways to exit :
Return value is pressed into upper call stack frame .
Exception information is thrown to the stack frame that can be handled .
PC The counter points to the next instruction after the method call .
4、Native Method Stacks( Native Method Stack )
Native Method Stack (Native Method Stack) stay JVM Memory layout , It's also Thread object private Of , But the virtual machine stack “ Main internal ”, And the local method stack “ Main external ”. This “ domestic and foreign ” Is aimed at JVM Speaking of , The local method stack is Native Method service . When a thread starts calling a local method , It's going to enter a place where it's no longer affected JVM The world of constraints . Local methods can be implemented through JVNI(Java Native Interface) To access the data area of the virtual machine runtime , You can even call registers , With and JVM Same ability and authority . When a large number of local methods appear , It's bound to weaken JVM Control of the system , Because its error messages are black box , Elusive . In the case of insufficient memory , The local method stack will still throw native heap OutOfMemory.
Key points JNI Class local method , The most common local method should be System.currentTimeMills(),JNI send Java Deep use of operating system features and functions , Reuse is not Java Code . But in the course of the project , If you use a lot of other languages to achieve JNI, You lose cross platform features , It threatens the stability of the program . If you need to interact with native code , The intermediate standard framework can be used for decoupling , In this way, even if the local method crashes, it will not affect JVM The stability of the .
5、Program Counter Register ( Program count register )
In the program count register (Program Counter Register,PC) in ,Register The name of comes from CPU The register of ,CPU Only loading data into registers can run . Registers store field information about instructions , because CPU Time slice wheel limit , Many threads are executing concurrently , Any definite moment , A core in a processor or multi-core processor , Only one instruction in a thread will be executed .
This will inevitably lead to frequent interruption or recovery , How can we ensure that there is no difference ? After each thread is created , Will have their own Program counter and Stack frame , Program counter For storage Offset and line number indicator of execution instruction, etc , Thread execution or recovery depends on Program counter . Program counters do not affect each other among threads , There will be no memory overflow exception in this area .
summary
Last , From the point of view of threads , Heap and meta space are shared by all threads , And the virtual machine stack 、 Native Method Stack 、 The program counter is private inside the thread , Let's look at it from the perspective of threads Java Memory structure diagram of :

Only when you start , You will reach your ideal and destination , Only when you work hard ,
You will achieve brilliant success , Only when you sow , You will gain something . Only pursue ,
To taste the taste of success , Sticking to yesterday is called foothold , Sticking to today is called enterprising , Sticking to tomorrow is called success . Welcome all friends to praise + Collection !!!
I believe that through the study of this article , You should be right jvm Have a more comprehensive understanding .
You can see it here , Just click on it. Well .
边栏推荐
- The 35 required questions in MySQL interview are illustrated, which is too easy to understand
- I have been in the industry for 4 years and changed jobs twice. I have understood the field of software testing~
- How Oracle exports data (how Oracle backs up databases)
- 酷派主动终止针对小米公司的专利侵权诉讼
- Coolpad voluntarily terminated the patent infringement lawsuit against Xiaomi
- 株洲市九方中学开展防溺水、消防安全教育培训活动
- B+ tree height calculation of MySQL
- RHCSA第一天
- openEuler Embedded SIG | 分布式软总线
- Knowledge description framework of foreign patent documents based on knowledge elements
猜你喜欢

The ref value ‘xxx‘ will likely have changed by the time this effect function runs. If this ref......
![[极客大挑战 2019]Secret File&文件包含常用伪协议以及姿势](/img/aa/a169cdd8cc6cdfda6d2777511b4dd2.png)
[极客大挑战 2019]Secret File&文件包含常用伪协议以及姿势

Icml2022 | timing self-monitoring video transformer

Pytorch学习记录(四):过拟合、卷积神经网络CNN

基于Xception-TD的中华传统刺绣分类模型构建

Attribute based encryption simulation and code implementation (cp-abe) paper: ciphertext policy attribute based encryption

顺序表的实现

分而治之,大型文件分片上传

技术选型Rust——事后分析

LeetCode链表问题——面试题02.07.链表相交(一题一文学会链表)
随机推荐
Attribute based encryption simulation and code implementation (cp-abe) paper: ciphertext policy attribute based encryption
基于多模态融合的非遗图片分类研究
Skiasharp's WPF self drawn drag ball (case version)
Quii Cordova plugin telerik imagepicker plug-in multi image upload out of sequence
Adventures of little mouse: behind the scenes gags of moss 2
Coolpad voluntarily terminated the patent infringement lawsuit against Xiaomi
The ref value ‘xxx‘ will likely have changed by the time this effect function runs. If this ref......
Pytorch学习记录(四):过拟合、卷积神经网络CNN
日志瘦身神操作:从5G优化到1G到底是怎么做到的!(荣耀典藏版)
Pytorch learning record (4): over fitting, convolution neural network CNN
For the next generation chromebook, MediaTek launched new chipsets mt8192 and mt8195
C process control statement
An end-to-end aspect level emotion analysis method for government app reviews based on brnn
Top level "redis notes", cache avalanche + breakdown + penetration + cluster + distributed lock, Nb
Bus, protocol, specification, interface, data acquisition and control system in industrial communication field
中文招聘文档中专业技能词抽取的跨域迁移学习
1945. sum of digits after string conversion
How to understand data mesh
分而治之,大型文件分片上传
小霸王被申请破产!公司成“老赖” ,法人被限制高消费