当前位置:网站首页>Roll up and break through the anxiety of 35 years old. The animation demonstrates how easy it is for the CPU to record the function call process and enter the Internet factory
Roll up and break through the anxiety of 35 years old. The animation demonstrates how easy it is for the CPU to record the function call process and enter the Internet factory
2022-06-10 16:32:00 【51CTO】
hi Hello everyone , I am a DHL. official account :ByteCode , Focus on sharing interesting hard core original content ,Kotlin、Jetpack、 performance optimization 、 System source code 、 Algorithm and data structure 、 Animation 、 Big factory surface
The full text is divided into Video version and Text version ,
Video version :
Through voice and animation , Can see more intuitively , Memory records method calls and return procedures .
bilibili Address : b23.tv/TQXL4xx
Text version
Have we ever thought about it while writing code How to call 、 How to return after the method is executed 、 How memory records method calls . This is also the key content of this article today .
Method calls and return procedures involve , Virtual machine stack 、 Program counter 、 Local variable table 、 The stack of operands 、 Method return address 、 Dynamic links and so on , There are many knowledge points involved , At the same time, these contents are also high-frequency interview questions , So I will split it into several articles , Make a detailed analysis of each knowledge point . In today's article, we will focus on how memory records method calls and return procedures .
Virtual machine stack
Java Method in the form of stack frame , Running on the virtual machine stack (Java Stack ) in , The stack is thread private , When the program starts , Will create a main Threads , The operating system allocates a section of memory for each thread , A virtual machine stack will be created when the thread is created , The life cycle of virtual machine stack is the same as that of thread , The thread is over , The virtual machine stack is also destroyed .
Every Java Method , Corresponding to each stack frame , So the method starts and ends , It is the process of putting and leaving stack frames one by one , The effect is shown below .

Stack frame
Every Java Method , All are stack frames , Each stack frame contains : Local variable table 、 The stack of operands 、 Method return address 、 Dynamic links 、 Additional information .

- Local variable table : Save the method parameter list and local variables in the method , Store... In the declared order , It is shown as an array , If it's an example method , The index for 0 yes this References to , As shown in the figure below .

| Indexes (Slot) | name (Name) |
|---|---|
| 0 | this |
| 1 | num |
| 2 | res |
- The stack of operands : Save temporary results during method execution
- The return address : Save the pc Register value ( namely JVM Instruction address ), Used at the end of the method , Return to the use of transfer , Let the caller method continue to execute
- Dynamic links : A reference to the method to which the stack frame belongs in the runtime constant pool , That is, find the symbolic reference of the target method from the constant pool , Then convert to direct reference
Additional information : Like a program debug Some attachment information added during ( Is not important , Don't care , Negligible )
Here we only need to know their functions , Their data structure 、 Meaning of bytecode 、 Execution process, etc , In the following articles, I will make a detailed analysis of each knowledge point .
Method call procedure
First write a piece of code for method calls , The first call main() Call after method fun1() And then call fun2() , As shown in the figure below .

Now let's demonstrate Java The virtual machine performs these JVM Instruction process , The first call main () Method .
main () Method
main() Method execution process animation effect is as follows .

- Execution instruction
0: aload_0, From the local variable table , Read index as 0 Value , Push into the operand stack , Because it's an instance method , So the index is 0 The value of is this References to

- Execution instruction
1: iconst_5, Constant 5 Push into the operand stack

- Execution instruction
2: invokevirtual #7, Constant 5 and this Out of the operand stack , And then callthis.fun1(5)

First, find the method from the constant pool fun1() Symbol reference for , Then the symbolic references are converted into direct references through dynamic links , Then call this.fun1(5), The method fun1() Push into the virtual machine stack as a stack frame , Jump to fun1(), So let's keep going .
How to find the symbolic reference of the target method from the constant pool , Then it is converted into a direct reference procedure , It will be analyzed in detail in a later series of articles
Calling fun1() Before ,fun1() The local variable table and method return address of have been determined .

How to get in fun1 (int num)
Method fun1(int num) The animation effect of the execution process is as follows .

- Execution instruction
0: aload_0, From the local variable table , Read index as 0 Value , Push into the operand stack . Because it's an instance method , So the index is 0 The value of is this References to

- Execution instruction
1: iload_1, From the local variable table , Read index as 1 Variable num Value , And push in the operand stack

- Execution instruction
2: invokevirtual #13,num and this Out of the operand stack , And then callthis.fun2(num)

First, find the method from the constant pool fun2() Symbol reference for , Then the symbolic references are converted into direct references through dynamic links , Then call this.fun2(num), The method fun2() Push into the virtual machine stack as a stack frame , Jump to fun2(), So let's keep going , call fun2() Before ,fun2() The local variable table and method return address of have been determined .

How to get in fun2 (int num)
Method fun2(int num) The animation effect of the execution process is as follows .

- Execution instruction
0: iload_1, From the local variable table , Read index as 1 Variable num Value , And push it into the operand stack

- Execution instruction
1: bipush, Constant 10 Push into the operand stack

- Execution instruction
3: iadd,num And constants 10 Out of the operand stack , And then add , Push the result into the operand stack

- Execution instruction
4: istore_2, Take the result from the operand stack , And assign a value to the index in the local variable table as 2 The variable of res2

- Execution instruction
5: iload_2, From the local variable table , Read index as 2 The variable of res2 Value , And push it into the operand stack

Method to exit the process
Each method is a stack frame , Each stack frame saves the method return address , perform return Series of instructions , The return address saved according to the current stack frame , Return to the location of the call , So let's keep going . So there are two situations .
Abnormal exit
If an exception occurs and is caught , Will look up from the exception table PC The address of the register (JVM Instruction address ), Return to the call and continue to execute .

The following things will be done during normal exit
- Restore the local variable table of the previous stack frame 、 The stack of operands
- If there is a return value , Push the return value into the operand stack of the caller stack frame , Whether there is a return value depends on
returnJVM Instructions :ireturn: The return value isboolean、byte、char、shortandinttypelreturn: The return value isLongtypefreturn: The return value isFloattypedreturn: The return value isDoubletypeareturn: The return value is a reference typereturn: The return value type isvoid
- Set the caller stack frame JVM Instruction address
- The current stack frame comes out of the virtual machine stack
In this article, we only analyze the normal exit process , The process of abnormal exit and normal exit is roughly the same . The animation effect of normal exit process is as follows .

- Method
fun2At the end , Execute the last instructionireturn, The current stack frame comes out of the virtual machine stack , The return address of the method saved according to the current stack frame , Back to fun1 , recovery fun1 The local variable table of 、 The stack of operands , Results will be returnedres2Save to caller (fun1) In the operand stack

- Back to the method
fun1(int num), Execution instruction5: istore_2, Variableres2Out of the stack from the operand , The index assigned to the local variable table is 2 The variable ofres1

- Execution instruction
6: iload_2, From the local variable table , Read index as 2 Variableres1Value , And push it into the operand stack

- Execution method fun1 The last instruction
7: ireturn, The current stack frame comes out of the virtual machine stack , The return address of the method saved according to the current stack frame , Back to main Method , recovery main Method's local variable table 、 The stack of operands , Results will be returnedres2Save to caller (main) In the operand stack

- Finally, go back to the method
mainin , Execute the last instruction5: pop, The elements in the operand stack are out of the stack

- Execute the last instruction
6: return, So far, all the method calls are over , Method , Will also be returned to the system

Each method call , That is, the process of stack frame entering and leaving the stack , It also needs to occupy part of the memory , Used to save the local variable table 、 The stack of operands 、 Method return address 、 Dynamic links 、 Additional information, etc .
When the method is executed , That is, the stack frame comes out of the stack , Memory occupied by method calls , Will also be returned to the system .
This is the end of the article , Thanks for reading , If it helps , welcome Looking at 、 give the thumbs-up 、 Collection 、 Share To my friends .
I sincerely recommend you to pay attention to me , official account :ByteCode , Continue to share hard core original content ,Kotlin、Jetpack、 performance optimization 、 System source code 、 Algorithm and data structure 、 Animation 、 Big factory surface .
边栏推荐
- Zhangxiaobai teaches you how to use Ogg to synchronize Oracle 19C data with MySQL 5.7 (3)
- Detailed explanation of RGB color space, hue, saturation, brightness and HSV color space
- Driver development and abnormal analysis of "technical dry goods" industrial touch screen (serial)
- Online document collaboration tool is the first step to improve work efficiency
- MapReduce之Map阶段的join操作案例
- Four Byron poems translated from heartless sword
- What are the pitfalls of redis's current network: using a cache and paying for disk failures?
- Research Report on development potential analysis and investment development strategy of global and Chinese hydraulic oil industry (2022-2028)
- 【历史上的今天】6 月 10 日:Apple II 问世;微软收购 GECAD;发明“软件工程”一词的科技先驱出生
- 2D pose estimation for pose estimation - (openpose) realtime multi person 2D pose estimation using part affinity fields
猜你喜欢

Devops-2- from the Phoenix Project

Add Anaconda's bin directory to path

PV operation daily question - single log bridge problem

【历史上的今天】6 月 10 日:Apple II 问世;微软收购 GECAD;发明“软件工程”一词的科技先驱出生
![[today in history] June 10: Apple II came out; Microsoft acquires gecad; The scientific and technological pioneer who invented the word](/img/0d/9f99eb3dcb73c912987b81fba71890.png)
[today in history] June 10: Apple II came out; Microsoft acquires gecad; The scientific and technological pioneer who invented the word "software engineering" was born

硬件仪器的使用

Rk3308-- firmware compilation

Weilai quarterly report diagram: the revenue was 9.9 billion yuan, a year-on-year increase of 24%, and the operating loss was nearly 2.2 billion yuan
![Jerry's ble dynamic power regulation [chapter]](/img/29/22be6dca25c4e6502f076fee73dd44.png)
Jerry's ble dynamic power regulation [chapter]
![[MySQL basics]](/img/fc/48e9c6b739e29472a7a103e47663af.png)
[MySQL basics]
随机推荐
Four Byron poems translated from heartless sword
MapReduce案例之排序
[section 14 STL container II]
2D pose estimation for pose estimation - (openpose) realtime multi person 2D pose estimation using part affinity fields
[object].
Sorting of MapReduce cases
Query convert quickview is a grayed out solution (turn)_ SAP LIUMENG
Meetup review how Devops & mlops solve the machine learning dilemma in enterprises?
Pytorch installation tutorial
Investment prospect and development strategy planning of China's waste power generation equipment industry 2022-2028 Edition
Exploration of kangaroo cloud data stack on spark SQL optimization based on CBO
The CPU load caused by implicit conversion is nearly 100%
2D human posture estimation for posture estimation - simple baseline (SBL)
Aggregate sum of MapReduce cases
Customization development of defi cross chain mining DAPP system
「技术干货」工业触摸屏之驱动开发及异常分析(连载)
【历史上的今天】6 月 10 日:Apple II 问世;微软收购 GECAD;发明“软件工程”一词的科技先驱出生
软件测试架构师,给后辈的16条忠告,快看看别错过
RK3308 按键Key与LED灯
Apache atlas quick start