Java / JDK, JRE, JVM, JIT
Difference between Stack and Heap memory in Java.
The main difference between heap and stack is that stack memory is used to store local variables and function call while heap memory stores objects in Java.
Each Thread in Java has its own stack whose size can be specified using -Xss JVM parameter, similarly, you can also specify heap size of Java program using JVM option -Xms and -Xmx where -Xms is the starting size of the heap and -Xmx is the maximum size of java heap.
If there is no memory left in the stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating an object, JVM will throw java.lang.OutOfMemoryError: Java Heap Space.
Size of stack memory is a lot lesser than the size of heap memory in Java.
Variables stored in the stack are only visible to the owner thread while objects created in the heap are visible to all threads. Stack memory is a private memory of a Java Thread while heap memory is shared among all threads.
| Stack | Heap |
| Stack memory is used only by one thread of execution. | Heap memory is used by all the parts of the application. |
| Stack memory cannot be accessed by other threads. | Objects stored in the heap are globally accessible. |
| Follows LIFO manner to free memory. | Memory management is based on the generation associated with each object. |
| Exists until the end of execution of the thread. | Heap memory lives from the start till the end of application execution. |
| Stack memory only contains local primitive and reference variables to objects in heap space. | Whenever an object is created, its always stored in the Heap space. |
More Related questions...