Confused with Java memory management (stacks and heaps)

This may sound silly, but I still don't understand what Java Stack and heap of memory are. What I know from learning is the following:

1) All method calls go to the stack.

2) All allocated memory locally goes into a heap of memory (not very clear about this point)

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

The following cases bother me:

1) If I create an int variable in the method and return it where it goes (I believe that it goes on the stack, but needs clarification).

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

3) My problem is what will happen if I do not assign the object mentioned in clause 2 to some reference or I do not return it. Is it still created on the heap? Logically, this should be, but please enlighten me.

+4
source share
2 answers

All method parameters are pushed onto the stack. All local variables go onto the stack. The only thing that goes into the heap is the material explicitly allocated using new (or implicitly using automatic boxing or varargs.)

Another way to think about how primitive values ​​and link objects / arrays can go on the stack, but actual objects cannot 1 .

So:

1) - you return a primitive value (and not a variable!), And it goes onto the stack. (You cannot β€œreturn” a variable. This variable is part of the stack frame and cannot be separated from it.)

2) Yes.

3) Yes, at least for the moment 1 . At some point, the GC may work, note that the application no longer refers to the object and does not fix it.


1 - In fact, the latest Hotspot compilers are able to detect that an object reference never "escapes" the method that creates it, and that objects can be allocated on the stack. IIRC, this optimization, called escape analysis, must be activated using the JVM command line flag.

+8
source

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

Stack: object references and primitive variables are pushed onto the stack.

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

For all questions:

1) Yes

2) Yes

3) Yes

+1
source

Source: https://habr.com/ru/post/1412901/


All Articles