与Java内存管理混淆(堆栈和堆) [英] Confused with Java Memory Management (Stacks and Heaps)

查看:166
本文介绍了与Java内存管理混淆(堆栈和堆)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能听起来很愚蠢,但我仍然不清楚Java Stack和内存堆。我从学习中得知的是:

This might sound stupid but I am still not clear about the Java Stack and the memory heap. What I know from studying is following:

1)所有方法调用都在堆栈上。

1) All the method calls goes on stack.

2)本地分配的所有内存都在内存堆上(关于这一点不是很清楚)

2) All the memory allocated locally goes on memory heap (not very clear about this point)

3)新运算符分配的所有内存(在方法或类中) )继续记忆堆。

3) All the memory allocated by new operator (either in a method or in a class) goes on memory heap.

我担心以下情况:

1)如果我创建了一个方法中的int变量并返回它,它在哪里(我相信它在堆栈上,但需要澄清)。

1) If I create a int variable in a method and return it, where does it go ( I believe it goes on stack, but need clarification).

2)如果我在中创建一个新对象即使在方法执行结束后,它仍然存在于堆内存中的方法(我理解这是因为当我将此对象分配给某个外部引用变量或返回此对象时,java创建的对象的哈希码保持不变) 。

2) If I create a new object in a method it goes on heap memory as it exists even after the methods execution is over(I understand this happens because the hash code of the object created by java remains same when I assign this object to some external reference variable or I return this object ).

3)我的问题是如果我没有将第2点中提到的对象分配给任何引用,或者我没有返回它,会发生什么。它仍然是在堆上创建的吗?逻辑上应该是但请赐教。

3) My problem is what happens if I am not assigning the object mentioned in point 2 to any reference or I am not returning this. Is it still created on heap? Logically it should be but please enlighten me.

推荐答案

所有方法参数都在堆栈上。所有局部变量都在堆栈上。堆中唯一的东西是使用 new 显式分配的东西(或者通过自动装箱或varargs隐式分配。)

All method parameters go on the stack. All local variables go on the stack. The only thing that goes in the heap is stuff allocated explicitly using new (or implicitly by auto-boxing or varargs.)

考虑它的另一种方法是原始值和对象/数组引用可以在堆栈上,但实际对象不能 1

Another way to think about it is that primitive values and object/array references may go on the stack, but actual objects cannot1.

所以:

1) - 你正在返回一个原始值(不是一个变量!),它会进入堆栈。 (你不能返回一个变量。变量是堆栈框架的一部分,不能与它分离。)

1) - you are returning a primitive value (not a variable!), and it goes on the stack. (You can't "return" a variable. The variable is part of the stack frame and can't be detached from it.)

2)是。

3)是的,至少现在 1 。在某些时候,GC可能会运行,注意应用程序不再引用该对象,并回收它。

3) Yes, at least for now1. At some point, the GC may run, notice that the application doesn't have a reference to the object any more, and reclaim it.

1 - 实际上,最新的Hotspot编译器能够检测到对象的引用永远不会从创建它的方法中逃脱,并且可以在堆栈上分配对象。 IIRC,需要使用JVM命令行标志启用此优化 - 称为转义分析。

这篇关于与Java内存管理混淆(堆栈和堆)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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