java - Pushing variables to Stack and Variables living in the Stack difference? -
so know there exists 2 memory areas: stack , heap.
i know if create local variable live in stack, not in heap. stack grow push data in:
now try pass confusion having you:
for example simple java code:
public class testclass { public static void main(string[] args) { object foo = null; object bar = null; } }
is translated byte code:
public static void main(java.lang.string[]); code: stack=1, locals=3, args_size=1 0: aconst_null 1: astore_1 2: aconst_null 3: astore_2 4: return linenumbertable: line 5: 0 line 6: 2 line 7: 4 localvariabletable: start length slot name signature 0 5 0 args [ljava/lang/string; 2 3 1 foo ljava/lang/object; 4 1 2 bar ljava/lang/object;
where definition acons_null is:
push null reference onto stack
and astore_1 is:
store reference local variable 1
the confusion having is, pushed foo stack, stored in stack again? meant storing reference in local variable? local variable live? same stack pushed foo or these seperate stacks?
now @ point, if call method on first object pushed stack, since stack pointer pointing last element pushed, how processed?
there exists 1 stack per thread in jvm. each stack composed of several frames: each method invocation creates new frame, , when method invocation done, frame destroyed.
within stack frame there 2 areas :
- the operand stack (don't confuse word "stack" here jvm stack -- stack here denotes area last-in-first-out structure).
- an array of local variables each variable has index (starting @ zero).
depending on jvm implementation, may or may not contiguous in memory. logically 2 separate sections of stack frame.
as explained in description of aconst_null
, aconst_null
instruction pushes null
object reference onto operand stack.
and explained in description of astore_<n>
(where n
0, 1, 2 or 3):
the
<n>
must index local variable array of current frame (§2.6).objectref
on top of operand stack must of typereturnaddress
or of typereference
. it popped operand stack, , value of local variable @<n>
setobjectref
.
so in example, statement object foo = null
translates following:
- push
null
(a special reference points "nothing") onto top of operand stack.
operand stack __________ | null | <-- null pushed on operand stack |__________| | | |__________| | | |__________|
- pop reference operand stack , store in local variable @ index 1. local variable corresponds
foo
.
operand stack local variables __________ _______________ _______________ _______________ _______________ | | | args | foo (null) | | | |__________| |_______0_______|_______1_______|_______2_______|_______3_______| | | store null in lv#1 |__________| | | |__________|
same steps done object bar = null
except null
stored in local variable @ index 2.
source: java virtual machine specification (see this section).
Comments
Post a Comment