JVM - Heap and Stack
Asked Answered
B

3

6

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

Also where does the threads reside ?

Bloodless answered 13/5, 2010 at 11:3 Comment(0)
G
4

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.

Goldshell answered 13/5, 2010 at 11:6 Comment(3)
@Nirmal: It's nothing strange. It's the same behaviour across all runtimes be it C/C++ runtime or otherwise. So, I don't really understand "why" the "why" from your side :)Goldshell
"Any primitive type data... are on the heap" is a little confusing. The heap does store primitives if they are data members of objects.Collarbone
Yes. It does.. but then, as you mentioned, as part of Composites. However, the moment we access the data, it's first copied on to the stack. For example, for an Object with definition ComplexNumber { float real, float imaginary }, in a method doWork(ComplexNumber cn} { return cn.real * cn.real + float.imaginary * float.imaginary; } the values real/imaginary are first brought onto the stack unline cn where only the reference is brought onto the stackGoldshell
C
4

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.

Claudeclaudel answered 29/9, 2011 at 12:41 Comment(0)
H
-1

Primitives :Stack

Objects : Heap

Threads : Have a separate stack while share the same heap.

Haematopoiesis answered 29/9, 2011 at 13:40 Comment(1)
aren't primitives are stored on the heap if they are instance variables? and on the stack if they are local variables?Treat

© 2022 - 2024 — McMap. All rights reserved.