当前位置:网站首页>JVM from getting started to abandoning 1: memory model
JVM from getting started to abandoning 1: memory model
2022-06-11 06:36:00 【__ LeoZhang】
1.JVM brief introduction
JVM yes Java Language implementation is the core of cross platform technology , We usually call it Java Run the required virtual machines . When we go through javac The order will Java Code compiled into .class After that, you can put them in JVM Running in . It is possible to run the same on different operating systems Java Code depends on jdk Implementation of different operating systems , Of course, the greatest hero here is JVM 了 . So what we are familiar with java The process that the code actually runs is like this .

2.JVM The memory model and the main blocks are introduced
According to the above brief introduction, we have roughly understood Java Where is the core foundation that can run across platforms , So today we focus on analyzing JVM How it works , How it works Java Code , And realize the same function on different operating systems .
First, let's take a look at JVM Memory structure .

With jdk1.8 The memory model after version is an example , The difference between this version and the earlier version is that 【 Forever 】 Turned into 【 Metadata 】, because JVM In the past, the constant pool ,static Variables and other information are managed in the permanent generation , As a result, the permanent generation will appear once the memory reaches the upper limit OOM The problem of , therefore 1.8 After that, the permanent generation is changed into a meta space, which is also to promote HotSpot JVM And JRockit VM Fusion , because JRockit There is no permanent generation .
Next, we will analyze the memory model in the figure above , We need to learn more about the heap and stack management mechanism .JVM Memory is divided into thread shared memory and thread private memory .

According to the above figure, we analyze that the storage location in the memory is also divided into public and private , because Java Is a multi-threaded execution language , It supports starting multiple threads to execute code at the same time , In this way, there are parameters and functions inside each thread , When multithreading is executed at the same time, the two links do not work together in essence , But through the application of time slice to carry out reciprocating operation , So we need to know where each thread is running , Therefore, the main function of the program counter is to record the address of the code execution location of each thread, so that when the thread switches, the previous progress can be continued for code execution . The main function of the memory space shared by threads is to record the variable information shared by different threads , This involves the knowledge of concurrent programming, which we will introduce separately in the following articles .
2.1 Virtual machine stack (JVM Stack)
The virtual machine stack is Java The container in which threads run , Every one of them Java Each thread corresponds to a virtual machine stack , The method on each thread is equivalent to a stack frame in the stack , Stack frame includes Java Details of the code run . except Native All methods except methods are put into JVM Is managed and executed in the stack of .
When starting a thread ( Including the main thread ), When a thread executes its internal code JVM The stack will start working , The program will push the functions of the current runtime into the stack layer by layer , The stack frame at the top of the stack is the function position to which the current program is executing , Because the capacity of the stack is limited, it will be triggered when too many functions are executed in the thread StackOverflow( Stack overflow ) abnormal , This exception is mainly reflected in incorrect recursive operations . The completed stack frame will be removed from the top of the stack , Until the stack is empty , Our program will be executed and enter the thread destruction stage . For the time being, we only consider non - NativeMethod The scene of the call . Please refer to the figure below for specific process .

That's it JVM After the stack execution process, we will introduce the important contents of the stack frame one by one .
2.1.1 Local variable table
The local variable table is used to store the parameters required by the stack frame function at runtime and the local variables inside the function , This involves the application of thread private and thread shared memory introduced above . Because each function will have corresponding parameters when it is running , When the local variable inside a function is of basic type, its position is the local variable table , If a variable inside a function stores a reference to an object , We only record the reference address of the object in the local variable table , Objects will be placed in JVM In the heap area of , Access by reference to address , This involves accessing the thread shared area .

2.1.2 Execution stack ( The stack of operands )
stay JVM After the stack frame of the virtual machine stack is created, an operand stack will be created for the stack frame , Its function is a space for executing the code inside each of our functions , Because each function contains its own process structure , This process can be short or long , These codes will execute the functions as a whole in the order of putting on the stack and putting out the stack . The simplest way here is through javap Command to execute a snippet of code .
package com.leozhang.test;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 2;
int c = 3;
int sum = a+b+c;
System.out.println(sum);
}
}Then we go to the command line section of the file and use javac The command compiles it into .class file
[email protected] test % javac Test.javaAnd then run javap -c Command to disassemble the code to see
[email protected] test % javap -c Test
Warning : file ./Test.class Does not contain classes Test
Compiled from "Test.java"
public class com.leozhang.test.Test {
public com.leozhang.test.Test();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_1 # Constant 1 Push into the operand stack
1: istore_1 # Constant 1 From the operand stack, put it in the... Of the local variable table 1 A place
2: iconst_2 # Constant 2 Push into the operand stack
3: istore_2 # Remove constants from the operand stack 2 Put it in the... Of the local variable table 2 A place
4: iconst_3 # Constant 3 Push into the operand stack
5: istore_3 # Remove constants from the operand stack 3 Put it in the... Of the local variable table 3 A place
6: iload_1 # The first position of the loaded local variable is placed at the top of the operand stack
7: iload_2 # The second position of the loaded local variable is placed at the top of the operand stack
8: iadd # Add the two data and place them at the top of the operand stack , That is to finish a+b=3
9: iload_3 # Place the third position of the local variable table at the top of the operand stack
10: iadd # Add the two variables of the current operand stack to the top of the operand stack , namely (a+b) Result +c=6
11: istore 4 # There is nothing to put on the stack , Put... At the top of the stack 6 Put it in the fourth position of the local variable table
13: getstatic #2 # obtain System Object's static variables out // Field java/lang/System.out:Ljava/io/PrintStream;
16: iload 4 # Place the fourth position of the local variable table at the top of the operand stack
18: invokevirtual #3 # perform System.out Of Print The function outputs the contents at the top of the stack // Method java/io/PrintStream.println:(I)V
21: return # Method end
}According to the above actual code execution, we can analyze the actual execution process of simple variable addition in memory from the perspective of assembly , These actions are all completed in the operand stack in the same stack frame .
2.1.3 Dynamic links
In fact, we have already used dynamic links , Its function is to execute the operation in the stack if the variables in the constant pool are encountered , We use dynamic links to access variables in the constant pool through memory addresses , The code above uses System.out Object this object is System Object out It is a static object , So this object is not stored on the stack while the program is running , It is reserved in the meta space when the program is initialized , To ensure that other programs do not need to create the object repeatedly when using it , So what we saw in the introduction above getstatic The function of is to bring the data in the constant pool to the stack for running .
2.1.4 Method return address
It's after the execution of the method , To return the value of the location of the next code to execute , That's the value of the program counter . The program is divided into normal return and abnormal return , When the program returns normally, the returned address can be used as the value of the program counter to record the position where the current code is executed , When the program exception returns, the data returned by this method will not be recorded in the stack , But the exception information will be recorded .
2.2 Native Method Stack
The local method stack is used to execute Native A stack of methods , According to the name, we can know JVM Stack is mainly used to execute Java Functions and processes in , The local method stack is used to execute Java Functions that cannot be performed by itself , Here we need the help of the operating system api 了 . So the local method stack is in Java If you need to call... During code running C++ And the ability of other languages to improve the running efficiency JVM The stack jumps out to the local method stack .

2.3 Memory division
2.3.1 Direct memory area
stay jdk1.8 Before JVM Constant pool in the memory model of ,static Variables and other information are placed in “ Method area ” Of , Also called the permanent generation . His return JVM Memory management for .
Method area :
stay 《Java Virtual machine specification 》 It only specifies the concept of method area and its role .HotSpot stay JDK8 Before A permanent generation has realized this concept . Used to store class information 、 Constant pool 、 Static variables 、JIT Compiled code and other data .
PermGen( Forever ) The metadata information of the class in the FullGC It may be collected when , But it's hard to be satisfied . Also for PermGen How much space is allocated because it's difficult to determine the size of the data . So officials are JDK8 Remove permanent generation .
The official explanation is to remove the permanent generation :
This is part of the JRockit and Hotspot convergence effort. JRockit customers do not need to configure the permanent generation (since JRockit does not have a permanent generation) and are accustomed to not configuring the permanent generation.
namely : Removing the permanent generation is for fusion HotSpot JVM And JRockit VM And the effort , because JRockit There is no permanent generation , There is no need to configure permanent generation .
According to the above information, we know that now jdk Put these past in JVM The data of the permanent generation is transferred to a new area , This area is called a meta space , It belongs to off heap memory in memory management , adopt Java Of NIO The technology is realized in JVM Directly through the operating system to open up memory space to save data , There is no limit to the data capacity of this space , Depends on the physical memory size of the operating system , But it can still go through -XX:MetaspaceSize and -XX:MaxMetaspaceSize To specify the size of the meta space , In addition to storing the data in the meta space, the direct memory area also stores JIT Just in time compilation code cache. Because the direct memory area is through Native Way to open up extra heap memory , So his reading and writing performance is not JVM Memory speed is fast . His relationship with the meta space is not congruent , They belong to an interdependent relationship .
2.3.2 Thread sharing
2.3.2.1 Meta space
The function of meta space has been introduced above , It mainly stores the class loading information before code execution , Constant pool of the system , The runtime constant pool of the system , Systematic static Variables, etc , These are all in JVM Data that the runtime may always use once it is created , So they will continue to occupy space and release a small amount , In the past, it was placed in the method area, that is, the permanent generation , But this can cause code to run over time , Memory grows slowly, resulting in OOM. So the meta space data in the new memory model is arranged in the off heap memory, that is, the direct memory area mentioned above , In this way, the content of our meta space is not directly related to JVM For management, it only receives the limit of operating system memory , In this way, he can use more memory space to reduce OOM Scene . However, if the data storage in the meta space exceeds the remaining space in the system memory, it will also be triggered OOM Of .
2.3.2.2 Pile up
A heap is an area of memory shared by threads , It is mainly used to store data inside objects , Due to the high dispersion or continuity of the data inside the object and the large memory occupation , So it's not about frequent operations on the stack . Such objects will be stored in the heap . The difference between heap and meta space is that heap stores mostly active objects . The active object here refers to the object created during the program running , These objects may not need to be used until they are created , There are also some that may last a long time after the program is created , So these objects don't just need to be stored , You also need a garbage collector GC Clean up , Otherwise, when the number of frequently created objects increases, the limited heap space does not have enough space to store them OOM Error of .
According to the structure and functional characteristics of heap, we divide heap memory into old generation and new generation
【 Old generation 】: Used to store Java Large objects during code execution , Long used objects , And the objects created here through the guarantee mechanism , Their characteristic is that they are used for a long time and do not need frequent garbage collection operations . Therefore, the old generation can also be understood as the memory space stored by the continuously used objects . When the storage space occupation of the older generation reaches the threshold, it will trigger once MajorGC It's also called (FullGC) Garbage collection , But the garbage collection performance of the older generation will be very low and have blocking effect . Therefore, the data garbage collection frequency of the older generation is relatively low .
【 The new generation 】: Used to store Java Frequently created objects and newly created objects during code running , For example, we are in the code new When an object is selected, it will give priority to the new generation . Unless the memory space of the new generation is insufficient or the space occupied by objects exceeds the threshold , Will put the object directly in the old generation . The new generation is divided into Eden District ,Survivor From Area and Survivor To District . Their relationship is the new generation of memory space = Eden(80%)+Survivor From(10%)+Survivor To(10%) The relationship between , The new generation of active objects are mainly stored in Survivor From and Eden District ,Survivor To The zone is always empty . Their relationship is 8:1:1. The Cenozoic era is characterized by the existence of a large number of living and dying objects , They may not be used immediately after they are created , So the Cenozoic is the memory area with the most frequent garbage collection . Specific garbage collection methods will be introduced in the following garbage collection chapters . The garbage collection algorithm he uses is MinorGC( It is also known as the mark duplication method )
Sum up JVM Total heap memory usage of = The new generation + Old generation
Usually the Cenozoic : Old generation =1:2, But this is the default state , We can use... In the development process JVM Parameter to specify the memory space occupied by the new generation and the old generation . According to different application scenarios, the parameters and proportions may be completely different .
2.3.3 Thread private
Thread private memory space mainly refers to the memory space used by the virtual machine stack during the running process , They mainly use stack storage , Load directly into the local variable table at run time , And it will be destroyed along with the stack frame .
3. Other memory parts look forward
3.1 JIT Introduce
When JIT When compilation is enabled ( Enabled by default ),JVM Read in .class After the explanation of the document , Send it to JIT compiler .JIT The compiler compiles bytecode into machine code .
Usually javac Compile the program source code , convert to java Bytecode ,JVM Translate bytecode into corresponding machine instructions , Read in... One by one , Article by article interpretation and Translation . Obviously , To execute after explanation , Its execution speed must be slower than the executable binary bytecode program . In order to improve the execution speed , Introduced JIT technology .
At run time JIT Will save the translated machine code , Ready for next use , So in theory , Use this JIT Technology can , It can be close to the previous pure compilation technology .
3.2 Class loader Introduction
Java The function of the class loader is to load classes into the virtual machine at run time , First of all, no matter what kind of java The application must be made up of many class Make up the implementation , Different functions class It's different ( You said I put all the functions in one class Inside , you are great! ), For example, when our entry function is called , The entry function uses other class( Static code block 、 example ) The function of , At this time, the class loader will load the required classes into memory on demand , Class loaders are not all at once class Load into memory , It's loading on demand . Class loader loads class The principle of : entrust 、 Visibility and oneness .
Here is just a simple beginning , Class loaders are described in detail in subsequent articles .
3.3 Ignored garbage collection
stay JVM The heaviest module in the memory model is the garbage collection module. We have mentioned the related ideas of garbage collection in the above memory introduction , This paper mainly introduces the memory structure and model , The garbage collection mechanism will be introduced in the following articles .
边栏推荐
- 修复鼠标右键没有vscode快捷入口的问题
- Résoudre le problème de la durée inexacte du fichier audio AAC obtenu par ffmpeg
- Shandong University machine learning final 2021
- Handwriting promise [03] - realize multiple calls and chain calls of then method
- JS two methods to determine whether there are duplicate values in the array
- Chapter 6 of machine learning [series] random forest model
- Array de duplication....
- fatal: refusing to merge unrelated histories
- The nearest common ancestor of 235 binary search tree
- Graphsage paper reading
猜你喜欢

About the principle and code implementation of Siou (review IOU, giou, Diou, CIO)
![[]==![]](/img/65/ab724c74b080da319ed5c01c93fdb7.png)
[]==![]

Shandong University machine learning experiment 5 SVM

FPGA interview notes (II) -- synchronous asynchronous D flip-flop, static and dynamic timing analysis, frequency division design, retiming

The nearest common ancestor of 235 binary search tree

Graphsage paper reading

Learn C language well from keywords

FPGA interview notes (IV) -- sequence detector, gray code in cross clock domain, ping-pong operation, static and dynamic loss reduction, fixed-point lossless error, recovery time and removal time

What is sentinel produced by Ali?

Vulnhub's breach1.0 range exercise
随机推荐
Multimedia框架解析之MediaExtractor源码分析(一)
About the principle and code implementation of Siou (review IOU, giou, Diou, CIO)
Chapter 4 of machine learning [series] naive Bayesian model
节流和防抖
Sentinel annotation support - @sentinelresource usage details
Handwriting promise [03] - realize multiple calls and chain calls of then method
Jenkins voucher management
jenkins-用户权限管理
[]==! []
解决ffmpeg获取AAC音频文件duration不准
Learn C language well from keywords
100. same tree
搜狐员工遭遇工资补助诈骗 黑产与灰产有何区别 又要如何溯源?
ERROR 1215 (HY000): Cannot add foreign key constraint
Communication between different VLANs
How to treat the ethical issues arising from driverless Technology
Autojs, read one line, delete one line, and stop scripts other than your own
QT socket设置连接超时时间
538. convert binary search tree to cumulative tree
Teach everyone how to implement an electronic signature