2

As part of learning, from the below example,

enter image description here

My question:

Withe given memory layout of array declaration/definition, I would like to understand, Which memory space will be part of Stack space & Heap space? To be precise, Where does the below memory space(part of above diagram) sit?

enter image description here

2 Answers 2

3

Objects are always declared on the heap. Only references to objects are past around on the stack via method variables and parameters.

Thus the object graphs that you have diagrammed above will be stored on the heap and references to those objects will only exist on the stack during method invocation if and only if they have a parameter or variable that points to an object in the above diagrams.

JVM optimisations may vary this slightly under the hood, such as using registers instead of a stack or inlining an object as it can be shown to never escape a method call etc. However those optimizations may or may not occur, and they are not visible from the Java language level. Thus the above rule of the Java language holds, objects on the heap and method parameters/fields on the stack. Parameters and fields can never hold an object, only references to an object.

Sign up to request clarification or add additional context in comments.

11 Comments

actually HotSpot JVM starting from version 6u23 supports (and has enabled by default) escape analysis which decides whether it will allocate new objects on the heap or stack
@MateuszDymczyk true, I also recall from a talk by Brian Goetz that in some cases an object may not even get allocated at all as it could be unrolled entirely.
so, the subset diagram that is mentioned at bottomw of the query goes in stack?
@overexchange, sorry, I do not understand the question. What do you mean by "subset diagram", and "bottomw"? I could not find reference to them anywhere else in this question.
I have two diagrams in the query. Is the memory location that is shown in second diagram is part of Stack space?
|
1

THUMB-RULE - All objects are created on the heap irrespective of where they are instantiated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.