虚拟机栈
Each Java Virtual Machine thread has a private Java Virtual Machine stack, created at the same time as the thread. A Java Virtual Machine stack stores frames. A Java Virtual Machine stack is analogous to the stack of a conventional language such as C: it holds local variables and partial results, and plays a part in method invocation and return. Because the Java Virtual Machine stack is never manipulated directly except to push and pop frames, frames may be heap allocated. The memory for a Java Virtual Machine stack does not need to be contiguous.
每个线程创建时都会创建一个私有的虚拟机栈,栈中存储一个个栈帧,一个栈帧对应一个java方法。
栈与堆
栈主要作为运行时单位,堆主要作为存储单位。
作用
主管java程序运行,管理方法的局部变量(8中基本数据类型、对象的引用地址(堆空间中))、方法部分结果、方法调用和返回
- 局部变量 成员变量
- 基本数据变量 引用类型变量
特点
- 线程私有
- 存储栈帧(基本存储单位)
- 只有出栈、入栈操作
- 每个栈帧对应java源代码中要执行的一个方法
- 方法调用就对应栈操作
优点
- 栈是一种速度快、效率高的存储数据结构
- 栈的操作简单,方法执行入栈、方法执行结束后出栈
- 栈不存在垃圾回收问题(执行完就出栈,没有需要回收的垃圾。如果超过内存上限只会溢出)
栈帧
虚拟机栈中存储的基本单位叫栈帧,每一个栈帧对应这一个方法。入栈即是方法调用,出栈即是方法返回。因为栈帧对应着一个方法,所以栈帧拥有局部变量表、方法返回地址、操作数栈等结构。
常见异常
-
StackOverFlowError:栈溢出,线程请求的容量超过了jvm允许的最大栈容量,导致栈溢出。
可能原因:无法跳出的递归方法
-
OutOfMemoryError:虚拟机栈可以动态扩展,但是如果超过了操作系统为jvm分配的最大内存会出现OutOfMemoryError,即内存溢出异常。或者是已经达到了最大内存再去创建新线程的新虚拟机栈也会出现OOM异常。