简体   繁体   中英

When i create a stack in the program, why it is storing in heap not stack?

If I create a stack in a java method using Deque<Integer> stack = new LinkedList<Integer>(); Why does this stack variable store in the heap but not in the stack?

Java Heap Space

Java Heap space is used by java runtime to allocate memory to Objects and JRE classes. Whenever we create any object, it's always created in the Heap space.

Garbage Collection runs on the heap memory to free the memory used by objects that doesn't have any reference. Any object created in the heap space has global access and can be referenced from anywhere of the application.


Java Stack Memory

Java Stack memory is used for execution of a thread. They contain method specific values that are short-lived and references to other objects in the heap that are getting referred from the method.

Stack memory is always referenced in LIFO (Last-In-First-Out) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method.

As soon as method ends, the block becomes unused and become available for next method. Stack memory size is very less compared to Heap memory.


So when you use Deque stack = new LinkedList<>() , Deque stack is stack according to data model, but according to JVM this is just another object , like new Object() , new ArraList<>() etc. And these objects are stored in the heap .

See details in Java Heap Space vs Stack – Memory Allocation in Java

Some languages like C allow you to choose whether to allocate memory on the stack or the heap. There are a number of attractive reasons why one might want to use the stack. Memory allocated on the stack is automatically free d when the stack frame is "popped" (the function returns). You also get better performance because the stack is a contiguous chunk of memory, whereas memory can be allocated anywhere on the heap. It's easier for the compiler to optimize.

However, like many aspects of C , here there be dragons. There is no possibility of thread safety or sharing data. Whatever you allocate on the stack necessarily can't survive beyond the life of the function call. Objects on the stack are freed when the function returns, so if you need to return an object from a function it must be allocated on the heap.

Stack allocation can be dangerous and requires a low-level understanding of your program's memory usage. These go against the design principles of Java, namely that you should be able to let the computer handle memory management for you. Therefore the language designers just decided to not let you do it. As Oleg already shared, in Java all objects are allocated on the heap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM