当前位置:网站首页>Scalpel like analysis of JVM -- this article takes you to peek into the secrets of JVM
Scalpel like analysis of JVM -- this article takes you to peek into the secrets of JVM
2022-07-06 03:47:00 【Ten leaves Zhiqiu】
List of articles
One 、JVM The implementation process of
- The program should be executed before java Code into bytecode (class file )
- JVM First, the bytecode needs to be classed into a loader in a certain way (ClassLoader) Load the file into the runtime data area of memory (Runtime Data Area)
- The bytecode file is JVM A set of instruction set specifications , It can't be executed directly by the underlying operating system , So you need a specific command parser execution engine (Execution Engine) Translate the bytecode into the underlying system instructions and submit them to CPU To carry out
- In this process, you need to call the local library interface of the interface of other languages (Native Interface) To implement the function of the entire program , This is the 4 Responsibilities and functions of the three main components .
The diagram is as follows :
You can see ,JVM It is mainly implemented through four parts Java programmatic :
- Class loader (ClassLoader)
- Run time data area (Runtime Data Area)
- Execution engine (Execution Engine)
- Local library interface (Native Interface)
These contents are introduced in detail below .
Two 、 JVM Run time data area
JVM The runtime data area is also called memory layout , But it should be noted that it and Java Memory model ((Java Memory Model, abbreviation JMM) Completely different , Belong to two completely different concepts .
We can see from the figure below , This runtime data area consists of five parts , They are the method area 、 Virtual machine stack 、 Native Method Stack 、 Pile up 、 Program counter .
Now let's introduce the specific work of these five parts one by one . First, insert a knowledge point —— Thread private .
because JVM Multithreading is realized by switching threads in turn and allocating processor execution time , So at any given moment , A processor ( A multi-core processor is a kernel ) Will only execute an instruction in a thread . Therefore, in order to return to the correct execution position after switching threads , Each thread requires a separate program counter , Counters between threads do not affect each other , Independent storage . We call areas like this " Thread private " Of memory .
1. Program counter ( Thread private )
effect :
The smallest area in memory , Where is the next instruction saved .
The instructions in this are byte codes , When the program is running ,JVM These bytecodes will be loaded , Put it in memory , Then the program will send these instructions one by one ( Bytecode ) Take it out of memory , Put it in CPU On the implementation .
It is for this reason , Just need to remember which instruction is currently executed , Therefore, a program counter is needed to record .
And our computer brain CPU It is a parallel execution program , Need to be responsible for all threads . The operating system schedules execution in the unit of threads , Each thread has to record its execution location , therefore , Each thread is assigned a program counter .
If the current thread is executing a Java Method , This counter records the address of the virtual machine bytecode instruction being executed ; If what is being implemented is a Native Method , This counter value is empty .
2. Stack ( Thread private )
effect :
Simply put, it is to store local variables and method call information . Each time a new method is called , Will be involved once “ Push ” The operation of , Execute one method at a time , It's all about “ Out of the stack ” The operation of . Stack is also one for each thread .
for instance :
Green blocks on the top , We call it “ Stack frame ”. Each method creates a stack frame as it executes (Stack Frame) Used to store local variables 、 The stack of operands 、 Dynamic links 、 Method exit information ( In fact, it is the content of the box in the lower left corner of the above figure ). We often talk about heap memory 、 Stack memory , Stack memory refers to virtual machine stack .
Academic point to explain :
- Local variable table : It stores all kinds of basic data types known by the compiler (8 Big basic data types )、 Object reference . Local variable table
The required memory space is allocated during compilation , When entering a method , This method needs to allocate how much local variation in the frame
The quantity space is completely definite , The size of the local variable table will not be changed during execution . Simply put, it is to store method parameters and local variables
The amount . - Stack operation : Each method generates a first in and last out operation stack .
- Dynamic links : Method reference to the runtime constant pool .
- Method return address :PC The address of the register
actually , The stack space is relatively small , Although in JVM The size of stack space can be configured in , But generally speaking, it's just a few M To dozens M, So the stack is likely to be full , At this time, the stack overflows .
The stack here is divided into Java Virtual machine stack and Native Method Stack . Java The virtual machine stack is for JVM The use of , The local method stack is for local methods . It's not that different .
3. Pile up ( Thread sharing )
The role of the heap :
All objects created in the program are saved in the heap .
There is only one copy of a process heap , Multiple threads share a heap . When we new When an object , This new The object is on the heap , And the member variables of the object are also on the heap . Local variables are on the stack .
The pile is divided into two areas : The new generation and the old generation , The new generation puts new objects , After a certain time GC ( Garbage collection ) Objects that survive after the number of times will be put into the old generation . And the new generation 3 Regions : One Endn + Two Survivor(S0/S1).
4. Method area ( Thread sharing )
The role of the method area :
Used to store class information loaded by virtual machine 、 Constant 、 Static variables 、 Real-time compiler compiled after the code and other data .
.java The file will be executed as .class file ( Binary bytecode ),.class Will be loaded into memory , It was JVM Constructed as a class object ( The process of loading is called " Class loading ")
The class object here , Just put it in the method area .
Our class object describes what this class looks like , Include the name of the class , Who's in it , What are the methods , What is the name and type of each member , yes public still private, What is the name of each method , What kind of , yes public also private, Method contains instructions …
There is another important thing in class objects , Static members .static Decorated member , Become " Class properties ". And ordinary members , be called “ Instance attributes ".
3、 ... and 、JVM Class loading
Simply speaking : Class loading is actually an important core function of designing a runtime environment .Java It can compile at once and run everywhere , An important part is class loading .
1. The execution flow of class loading
For a class , Its life cycle is : load , Connect , initialization , Use , uninstall . The connection includes : verification , Get ready 、 Analyze three parts .
For the picture above , front 5 The steps are in a fixed order and are also the process of class loading , In the middle 3 We all belong to the connection , Therefore, class loading is divided into the following steps :
- load
- Connect
(1) verification
(2) Get ready
(3) analysis - initialization
1.1. load (Loading)
【 Be careful 】“ load ”(Loading) Not a “ Class loading ”(Class Loading), The two are different .“ load ”(Loading) The stage is the whole “ Class loading ”(Class Loading) A stage in the process .
stay load (Loading) Stage ,Java There are three things virtual machines need to do :
- Through a class's fully qualified name , To get the binary byte stream that defines this class
- Convert the static storage structure represented by the byte stream into the runtime data structure of the method area
- Generate a representation of this class in memory java.lang.Class object , As the access to various data structures of this class in the method area .
1.2. verification (Verification)
Verification is the first step in the connection phase , The purpose of this stage is to ensure that Class Bytes of the file The information contained in the stream conforms to 《Java Virtual machine specification 》 All the constraints of , Make sure that the information will not endanger the security of the virtual machine itself when it is run as code . If you find that the data format read here does not conform to the specification , Class loading fails , And throw an exception .
Validation options :
- File format validation
- Bytecode verification
- Symbol reference validation …
1.3. Get ready (Preparation)
The preparation phase is formally defined for variables in the class ( That is, static variables , By static Decorated variable ) The stage of allocating memory and setting the initial value of class variables .
1.4. analysis (Resolution)
The parsing phase is Java The process of virtual machine replacing symbolic reference in constant pool with direct reference , That is, the process of initializing constants .
.class In file , Constants are centrally placed , Each constant has a number ..class In the structure of the document, the number is initially recorded . You need to find the corresponding content according to the number , Fill in class objects .
1.5. initialization (Initializing)
Initialization phase ,Java The virtual machine really starts to execute Java Program code , Transfer ownership to the application . The initialization phase is the process of executing class constructor methods .
2. Classic interview questions
Write the results of the following program :
Their thinking :
- The class loading phase executes static code blocks . To create an instance , You must load the class first
- Static code blocks are only executed once during the class load phase
- Construction methods and code blocks , Each instantiation will execute , The construction code block precedes the construction method
- The parent class is executed before , Subclasses are executed after
- Our procedure is from main Start execution .main Here is Test Methods . Therefore, execute main, You need to load Test.
So the answer is :
3. Parent delegation model
The parental delegation model is a part of class loading , This link is in Loading Stage (
Parent delegation model , It's about JVM Class loader in , How to give a fully qualified name to a class ( java.lang.String ) find .class Documentation process .
JVM Special objects are provided in , It's called a class loader , Responsible for class loading . Of course, the class loader is also responsible for the process of finding files .class file , There are many possible positions . Some should be put in JDK Directory , Some are put in the project directory , Others are in other specific locations …
therefore ,JVM It provides multiple class loaders , Each class loader is responsible for a partition . Default classloader , Mainly 3 individual :
- BootStrapClassLoader: Responsible for loading classes in the standard library (String,ArrayList, Random, Scanner…)
- ExtensionClassLoader: Responsible for loading JDK Extended classes .( It is rarely used nowadays )
- ApplicationClassLoader: Be responsible for loading the classes in the current project directory
Programs can also customize class loaders , To load classes in other directories , such as Tomcat The class loader is customized , Used to specifically load webapps Inside .class .
Simply speaking :
Parent delegation model , This describes the process of finding directories , That is, how the above class loaders work together .
3.1. What is the parent delegate model
If a class loader receives a class load request , It doesn't try to load the class itself first , Instead, delegate the request to the parent loader to complete , This is true of class loaders at every level , So all load requests should eventually be passed to the top-level boot loader , Only when the parent loader feeds back that it cannot complete the load request ( It did not find the required class in its search scope ) when , The child loader will try to load itself .
step :
- Consider loading java.lang.String
a. Program started , Enter the first ApplicationClassLoader Class loader
b.ApplicationClassLoader Will check , Whether its parent loader has been loaded . without , Just call the parent class loader ExtensionClassLoaderc. ExtensionClassLoader Will also check , Whether its parent loader has been loaded . without , Just call the parent class loader BootStrapClassLoader
d. BootStrapClassLoader Will also check , Whether its parent loader has been loaded , I have no father, so I scan the directory I am responsible for
e.java.lang.String This class can be found in the standard library . Directly by the BootStrapClassLoader Responsible for the subsequent loading process . The search process is over .
- Consider loading your own Test class ~
a. Program started , Enter the first ApplicationClassLoader Class loader
b.ApplicationClassLoader Will check , Whether its parent loader has been loaded . without , Just call the parent class loader ExtensionClassLoaderc. ExtensionClassLoader Will also check , Whether its parent loader has been loaded . without , Just call the parent class loader BootStrapClassLoader
d.BootStapGlss.oader Will also check , Whether its parent loader has been loaded , I have no father . So I scan my own directory . No scan ! Go back to the sub loader and continue scanning
e. ExtensionClassLoader Also scan your own directories , No scan , Go back to the sub loader and continue scanning .
f. ApplicationClassLoader Also scan your own directories , Can find Test class , Then the subsequent loading . The link of finding the directory ends .
The above set of search rules , This is called “ Parent delegation model ”.
3.2. The advantages of the parental delegation model
- Avoid repeatedly loading classes : such as A Classes and B Classes have a parent class C class , So when A When started, it will C Class is loaded , So in B Class does not need to be loaded repeatedly C The class .
- Security : Using the parental delegation model can also ensure Java At the heart of API Not tampered with , If you don't use the parental delegation model , But each class loader will have some problems when it loads itself , For example, we write a program called java.lang.Object Class words , So when the program is running , There will be many different systems Object class , And some of them Object Class is provided by users themselves, so the security cannot be guaranteed .
End !
边栏推荐
- Map sorts according to the key value (ascending plus descending)
- 施努卡:什么是视觉定位系统 视觉系统如何定位
- 2. GPIO related operations
- Mathematical modeling regression analysis relationship between variables
- 2.13 weekly report
- 数据分析——seaborn可视化(笔记自用)
- RT thread -- FTP of LwIP (2)
- User perceived monitoring experience
- Record the process of reverse task manager
- MySQL 中的数据类型介绍
猜你喜欢
登录mysql输入密码时报错,ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: NO/YES
3.1 detailed explanation of rtthread serial port device (V1)
Python implementation of maddpg - (1) openai maddpg environment configuration
施努卡:视觉定位系统 视觉定位系统的工作原理
1.16 - check code
BUAA计算器(表达式计算-表达式树实现)
[risc-v] external interrupt
Pytorch基础——(1)张量(tensor)的初始化
mysql关于自增长增长问题
KS008基于SSM的新闻发布系统
随机推荐
关于非虚函数的假派生
Blue style mall website footer code
Factors affecting user perception
【Rust 笔记】18-宏
施努卡:什么是视觉定位系统 视觉系统如何定位
Shell pass parameters
Image super-resolution using deep convolutional networks(SRCNN)解读与实现
RT-Thread--Lwip之FTP(2)
Schnuka: what is visual positioning system and how to position it
Serial port-rs232-rs485-ttl
Error 1045 (28000): access denied for user 'root' @ 'localhost' (using password: no/yes
MySQL about self growth
Plus d'un milliard d'utilisateurs de grandes entreprises comme Facebook ont été compromis, il est temps de se concentrer sur le did
[rust notes] 18 macro
pytorch加载数据
Blue Bridge Cup - Castle formula
C#(二十七)之C#窗体应用
2.2 STM32 GPIO operation
[slam] lidar camera external parameter calibration (Hong Kong University marslab) does not need a QR code calibration board
Map sorts according to the key value (ascending plus descending)