Whenever a class is loaded, what are stored in the heap and what are stored in the stack ?
Also where does the threads reside ?
Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution. Whenever an object is created, it's always stored in the Heap space and stack memory contains the reference to it.
Key DifferencesThe Heap Space contains all objects are created, but Stack contains any reference to those objects. Objects stored in the Heap can be accessed throughout the application. Primitive local variables are only accessed the Stack Memory blocks that contain their methods.
Stack and Heap memory are allocated to an application by the Java Virtual Machine (JVM). Stack Memory in Java is used for the execution of a thread and static memory allocation. Stack memory contains method specific primitive values and references to objects in the heap that are getting referred from the method.
The Java™ virtual machine (JVM) heap is an independent memory allocation that can reduce the capacity of the main memory heap. Every integration server creates its own JVM. The integration server uses the JVM to execute the internal administration threads that require Java. This usage is typically minimal.
Reference types are in heap.
Any primitive type data and references to values on heap (parameters / local variables of method) are on the stack.
Each thread has its own stack.
All threads in the application share same heap.
It's really easy:
Note that local variables can only hold references ("pointers") or primitive values. A local variable can't ever hold "an object".
Note that this view is what is defined in the JVM specification. A concrete JVM could allocate objects in a non-heap area if it wants to. For example: if it knows that a newly created object never escapes the current invocation, then it could put the instantiated object in the stack area. However, that's a very optimization that is not visible to the developer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With