However, according to this lecture from UC Berkley, if an object reference exists on the stack, it will not be garbage collection.
You're right. What you are missing is that the link no longer exists on the stack.
For code that creates an object on the stack:
StringBuilder ref1 = new StringBuilder("object1");
variable ref1 is stored on the stack in some memory cell:
0x403730: Stack Pointer -> 0x40372C: pointer to ref1 0x403728: saved value of EBP 0x403724: saved value of return address 0x403720
Now comes the following line:
StringBuilder ref2 = new StringBuilder("object2");
Where will the pointer to ref2 be stored? On the stack: yes. But where on the stack? In the same memory cell that was used for ref1 , of course !:
0x403730: Stack Pointer -> 0x40372C: pointer to ref2 0x403728: saved value of EBP 0x403724: saved value of return address 0x403720
It would be foolish to just push another value onto the stack:
Stack Pointer -> 0x403730: pointer to ref2 0x40372C: pointer to ref1 0x403728: saved value of EBP 0x403724: saved value of return address 0x403720
It would be stupid because ref1 no longer needed.
That's why ref1 has the right to garbage collection: there are no more links to it.
source share