JVM 在哪里存储原始变量? [英] Where does the JVM store primitive variables?

查看:33
本文介绍了JVM 在哪里存储原始变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java JVM 将原始变量存储在哪里,原始变量使用后使用的内存是如何释放的?

Where does the Java JVM store primitive variables, and how is the memory used by primitives freed after use?

我猜它在堆栈上?

推荐答案

简单的答案:它取决于变量的声明位置,而不是它的类型.

Simplistic answer: it depends on where the variable is declared, not on its type.

局部变量存储在堆栈中.实例和静态变量存储在堆上.

Local variables are stored on the stack. Instance and static variables are stored on the heap.

不要忘记,对于引用类型变量,变量的值是引用,而不是对象.(数组也是引用类型——所以如果你有一个 int[],值将在堆上.)

Don't forget that for reference type variables, the value of a variable is a reference, not the object. (Arrays are reference types too - so if you have an int[], the values will be on the heap.)

现在,这可能是一个过于简单的答案,因为智能虚拟机可能能够检测特定引用类型变量是否引用了永远无法逃避"当前方法的对象.如果是这种情况,它可能会将整个对象内联到堆栈中.

Now, this is potentially an overly simplistic answer, because a smart VM may be able to detect if a particular reference type variable refers to an object which can never "escape" the current method. If that's the case, it could potentially inline the whole object on the stack.

但是概念上这个模型是准确的.所以一个 int 类型的变量被声明为这样的实例变量:

But conceptually this model is accurate. So a variable of type int which is declared as an instance variable like this:

class Foo
{
    private int value;
    ...
}

将概念上存在于堆中,作为 Foo 的任何实例的数据的一部分.它将作为释放实例的一部分被释放——它只是代表 Foo 实例的数据块内的 4 个字节;它不需要单独的释放.

will conceptually live on the heap, as part of the data of any instance of Foo. It will be freed as part of freeing the instance - it's just 4 bytes within the block of data representing a Foo instance; it doesn't need separate deallocation.

这篇关于JVM 在哪里存储原始变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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