开发者

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开发者_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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜