Java本地变量,对象引用,实例变量在哪里

编程入门 行业动态 更新时间:2024-10-25 18:27:44
本文介绍了Java本地变量,对象引用,实例变量在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前正在学习Java,堆栈和堆的内存概念,我知道局部变量和方法调用存在于称为stack的地方.和对象生活在堆中.但是如果该局部变量包含一个对象怎么办?或有对象引用?

I am currently learning the memory concepts of java, the stack and the heap, I know that local variables and method calls lived in a place called stack. and objects lived inside a heap. but what if that local variable holds an object? or has an object reference?

public void Something(){ Duck d = new Duck(24); }

它仍然存在于堆栈中吗?实例变量在哪里?请保持简单.谢谢.

Does it still live inside a stack? and where do instance variables live? please keep it simple as possible. thank you.

推荐答案

局部变量d(分配在堆栈上)包含对类Duck的对象的引用.通常,对象是在堆上分配的.

Local variable d (allocated on stack) contains a reference to an object of class Duck. In general objects are allocated on the heap.

Java 6e14添加了对称为转义分析"的支持.当使用-XX:+DoEscapeAnalysis开关启用它时,如果JVM确定在一个方法中创建了一个对象,该对象仅在该方法中使用,并且没有引用该对象的方法来转义"该方法-也就是说,我们可以确保在方法完成后未引用该对象-JVM可以在堆栈上分配该对象(将其所有字段视为本地变量进行处理).在您的示例中可能会发生这种情况.

Java 6e14 added support for something called 'escape analysis'. When you enable it with -XX:+DoEscapeAnalysis switch, then if JVM determines that an object is created in a method, used only in that method and there is no way for reference to the object to 'escape' that method - that is, we can be sure that the object is not referenced after method completes - JVM can allocate it on stack (treating all its fields as if they were local variables). This would probably happen in your example.

字段是与对象的其余部分一起分配的,因此取决于转义分析结果.

Fields are allocated with the rest of the object, so on the heap or on the stack, depending of escape analysis results.

更多推荐

Java本地变量,对象引用,实例变量在哪里

本文发布于:2023-11-02 13:58:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552589.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   实例   对象   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!