开发者

JVM - Heap and Stack

开发者 https://www.devze.com 2022-12-29 23:28 出处:网络
Whenever a class is loaded, what are stored in the heap and what are stored in the stack ? Also where does开发者_Python百科 the threads reside ?Reference types are in heap.

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

Also where does开发者_Python百科 the threads reside ?


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:

  • 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.


Primitives :Stack

Objects : Heap

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

0

精彩评论

暂无评论...
验证码 换一张
取 消