Published on Oct 19, 2022
Java applications need a certain amount of RAM on a computer to run. Each time an object or variable is declared, it needs more RAM. Simply designating enough memory to hold every value declared and run each method would lead to a bloated application. To keep application memory requirements, lean, it is partitioned in ways that require less memory and allows the application to run more quickly. The Java Virtual Machine (JVM) divides memory between Java Heap Space and Java Stack Memory in a way that only uses memory that’s needed.
It is created by the Java Virtual Machine when it starts. The memory is used if the application is running. Java runtime uses it to allocate memory to objects and Java Runtime Environment (JRE) classes. When an object is created, it is always created in Heap and has global access. That means all objects can be referenced from anywhere in the application. The memory is allocated during the execution of instructions written by programmers. Note that the name heap has nothing to do with the heap data structure.
It is called a heap because it is a pile of memory space available to programmers to allocate and de-allocate. Every time we made an object it always creates in Heap-space and the referencing information to these objects is always stored in Stack-memory. Heap memory allocation isn’t as safe as Stack memory allocation because the data stored in this space is accessible or visible to all threads. If a programmer does not handle this memory well, a memory leak can happen in the program.
You should use a heap when you require to allocate a large block of memory. For example, if you want to create a large size array or big structure to keep that variable around f a long time then you should allocate it on the heap.
However, if you are working with relatively small variables that are only required until the function using them is alive. Then you need to use the stack, which is faster and easier.
Parameter | STACK | HEAP |
---|---|---|
Basic | Memory is allocated in a contiguous block. | Memory is allocated in any random order. |
Allocation and De-allocation | Automatic by compiler instructions. | Manual by the programmer. |
Cost | Less | More |
Implementation | Easy | Hard |
Access time | Faster | Slower |
Main Issue | Shortage of memory | Memory fragmentation |
Locality of reference | Excellent | Adequate |
Safety | Thread safe, data stored can only be accessed by the owner | Not Thread safe, data stored visible to all threads |
Flexibility | Fixed Size | Resizing is possible. |
Data type structure | Linear | Hierarchical |
Preferred | Static memory allocation is preferred in the array. | Heap memory allocation is preferred in the linked list. |
The views expressed in this document are those of the author and do not necessarily reflect the position of the London School of Emerging Technology. View the detailed policy Disclaimer for Student and Personal Websites