Confused with Java Memory Management (Stacks and Heaps)

随声附和 提交于 2020-01-13 04:15:38

问题


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) All the method calls goes on stack.

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

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

I am worried about the below cases:

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) 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) 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.


回答1:


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.)

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

So:

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) Yes.

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 - actually, the latest Hotspot compilers are capable of detecting that an object's reference never "escapes" from the method that creates it, and that the objects could be allocated on the stack. IIRC, this optimization - called escape analysis - needs to be enabled using a JVM command-line flag.




回答2:


Code Segment: Constant values are often placed directly in the program code segment.

Stack: Object references and primitive variables are placed on the stack.

Heap: Whenever you create an object, the storage is allocated on the heap when that code is executed.

For your questions:

1) Yes

2) Yes

3) Yes



来源:https://stackoverflow.com/questions/10629521/confused-with-java-memory-management-stacks-and-heaps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!