Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused with Java Memory Management (Stacks and Heaps)

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.

like image 686
dharam Avatar asked Jan 17 '23 15:01

dharam


1 Answers

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.

like image 132
Stephen C Avatar answered Jan 30 '23 12:01

Stephen C