JVM学习笔记(三)理解虚拟机栈和栈帧

 

5.理解Java虚拟机栈和栈帧

官网

栈帧:每个栈帧都对应一个被调用的方法,可以理解为方法的运行空间。

每个栈帧中包括局部变量表(Local Variables)、操作数栈(Operand Stack)、指向运行时常量的引用( the run-time constant pool)、方法返回地址(Return Address)和附加信息。

局部变量表:方法中定义的局部变量以及方法参数存放在这张表中。

局部变量表中的变量不可直接使用,如需使用,必须通过相关指令将其加载至**操作数栈**中作为操作数使用。

操作数栈: 以压栈和出栈的方式存储操作数

动态链接: 每一个栈帧都包含一个指向运行时常量池中该栈帧所属方法的引用,持有这个引用是为了支持方法调用过程中的动态链接。

方法返回地址:当一个方法开始执行后,只有两种方式可以退出,一、遇到方法返回的字节码指令;二、遇见异常,并且这个异常没有在方法内得到处理。

5.1 源码和编译代码

class Person{ 
private String name="Jack"; 
private int age; 
private final double salary=100; 
private static String address; 
private final static String hobby="Programming"; 
public void say(){ 
System.out.println("person say..."); 
}
public static int calc(int op1,int op2){ 
op1=3; 
int result=op1+op2; 
return result; 
}
public static void order(){ 
}
public static void main(String[] args){ 
calc(1,2); 
order(); 
} 
}

编译后代码, 查看官网解释名词

Compiled from "Person.java" 
class Person { 
... 
public static int calc(int, int); 
Code:
0: iconst_3 //将int类型常量3压入[操作数栈] 
1: istore_0 //将int类型值存入[局部变量0] 
2: iload_0 //从[局部变量0]中装载int类型值入栈 
3: iload_1 //从[局部变量1]中装载int类型值入栈 
4: iadd //将栈顶元素弹出栈,执行int类型的加法,结果入栈 
【For example, the iadd instruction (§iadd) adds two int values together. It 
requires that the int values to be added be the top two values of the operand stack, pushed 
there by previous instructions. Both of the int values are popped from the operand stack. 
They are added, and their sum is pushed back onto the operand stack. Subcomputations may be 
nested on the operand stack, resulting in values that can be used by the encompassing 
computation.】 
5: istore_2 //将栈顶int类型值保存到[局部变量2]中 
6: iload_2 //从[局部变量2]中装载int类型值入栈 
7: ireturn //从方法中返回int类型的数据 
... 
}
​

5.2 栈帧运行图解

5.3 栈指向堆

栈帧中有个变量,类型为引用类型,例如:Object obj = new Object();这就是典型的栈中元素指向堆中的对象。

5.4 方法区指向堆

方法区中存放静态变量,常量等数据。例:

private static Object obj = new Object();

5.5 堆指向方法区

方法区中会包含类信息,堆中会有对象,那么怎么知道对象是那个类创建的?

思考 :一个对象怎么知道它是由哪个类创建出来的?怎么记录?这就需要了解一个Java对象的具体信息咯。


When I let go of what I am , I become what I might be.
走出舒适圈,遇见更好的自己。

发布了91 篇原创文章 · 获赞 63 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/qq_38423105/article/details/104710300