Java本地变量,对象引用,实例变量在哪里 [英] Java Where do Local variables,Object references,instance variables

查看:181
本文介绍了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本地变量,对象引用,实例变量在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆