Re: Java Memory Model - reg.
jakarta....@gmail.com wrote:
I am new to Java Memory Model. I read that when I instantiate an
object the memory for the object will be allocated in Heap and the
identifier will be allocated in Stack.
For example:
Object myObj = new Object();
The memory for the myObj will be allocated in Heap.
and the reference memory address will be stored in Stack.
That's sort-of true but not really.
First, one use of the term "Java memory model" has nothing to do with heap vs.
stack - it refers to how multiple threads make memory activity visible to each
other. Bear that in mind while Googling. It is a very important topic, just
not what you are asking.
Now, Java does not make any promises about heap vs. stack - the JVM is free to
optimize certain allocations to the stack, or even out of existence altogether.
Conceptually all object instances live on the heap, and references from
objects, i.e., class and instance variables, will also live on the heap
because they are part of the class or object. However, there is no semantic
impact to that, and the physical reality can shift and change.
Automatic variables, those of method or block scope, are more likely to live
on the stack, but might in practice live their entire lives in registers. Or
both, depending on run-time circumstances at the point of invocation.
Conceptually one might as well think of automatic variables, return values,
arguments and such as living on the stack.
So the conceptual, and generally useful picture is similar to your guess, but
not quite the same. Not all references live on the "stack" - allocated memory
lives on the "heap", and may include references as class or instance
variables. Method arguments, return values and block-scoped variables live on
the "stack".
Much more important than phantasms of "stack" and "heap" are the Java
realities of "references" and "instances". References keep instances alive,
and immune to garbage collection (except for weak references and weaker - a
separate topic). The ideas of reference and instance will solve a lot more
bugs than the ideas of stack and heap.
--
Lew