Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JVM - Heap and Stack

Whenever a class is loaded, what are stored in the heap and what are stored in the stack ?

Also where does the threads reside ?

like image 877
Nirmal Avatar asked May 13 '10 11:05

Nirmal


People also ask

What are the differences between the stack and the heap in JVM?

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.

What is difference between heap and stack?

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.

Does Java have stack and heap?

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.

What is JVM heap?

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.


2 Answers

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.

like image 63
gvaish Avatar answered Oct 13 '22 10:10

gvaish


It's really easy:

  • objects (i.e. instances of classes) are always on the heap. They can't be anywhere else
    • fields are part of objects, so they also live on the heap.
  • local variables (including method/constructor) parameters are always on the stack. They can't be anywhere else.

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.

like image 23
Joachim Sauer Avatar answered Oct 13 '22 12:10

Joachim Sauer