What happens to the stack when exiting a method?(退出方法时堆栈会发生什么?)
问题描述
我正在阅读 堆栈和堆是什么以及在哪里?.我有点模糊的一件事是方法退出后堆栈会发生什么.以这张图片为例:
I was reading What and where are the stack and heap?. One thing I am a bit fuzzy on is what happens to the stack after a method exits. Take this image for example:
退出方法时堆栈被清除,但这意味着什么?堆栈上的指针是否刚刚移回堆栈的开头使其为空?我希望这不是一个太宽泛的问题.当堆栈从退出方法中清除时,我不确定幕后发生了什么.
The stack is cleared upon exiting the method, but what does that mean? Is the pointer at the stack just moved back to the start of the stack making it empty? I hope this is not too broad of a question. I am not really sure what is going on behind the scenes when the stack is cleared from exiting a method.
推荐答案
调用方法时,局部变量位于栈上.对象引用也存放在栈中,对应的对象存放在堆中.
When a method is called, local variables are located on the stack. Object references are also stored on the stack, corresponding objects are store in the heap.
堆栈只是一个内存区域,它有一个开始和结束地址.JVM(java虚拟机)有一个寄存器指向当前栈顶(栈指针).如果调用了新方法,则会在寄存器中添加一个偏移量以获取堆栈上的新空间.
The stack is just a region of memory, it has a start and end address. The JVM (java virtual machine) has a register which points to the current top of the stack (stack pointer). If a new method is called, an offset will be added to the register to get new space on the stack.
当一个方法调用结束时,堆栈指针会减少这个偏移量,这释放了分配的空间.
When a method call is over, the stack pointer will be decreased by this offset, this frees the allocated space.
局部变量和其他东西(如返回地址、参数...)可能仍在堆栈中,将被下一个方法调用覆盖.
Local variables and other stuff (like return address, parameters...) may still on the stack and will be overwritten by next method call.
顺便说一句:这就是 java 将所有对象存储在堆中的原因.当一个对象位于堆栈上,并且您将返回指向堆栈的引用时,该对象可能会被下一个方法调用销毁.
BTW: this is why java stored all objects in heap. When an object would be located on the stack, and you would return the reference which points to the stack, the object could be destroyed by next method call.
这篇关于退出方法时堆栈会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:退出方法时堆栈会发生什么?
基础教程推荐
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01