However according to this lecture from UC Berkley, as long as a reference to the object exists on the stack, it won't be garbage collected.
You're right. What you're missing is that a reference no longer exists on the stack.
For the code that constructs an object on the stack:
StringBuilder ref1 = new StringBuilder("object1");
the variable ref1
is stored on the stack, in some memory location:
0x403730:
Stack Pointer -> 0x40372C: pointer to ref1
0x403728: saved value of EBP
0x403724: saved value of return address
0x403720
Now comes the next line:
StringBuilder ref2 = new StringBuilder("object2");
Where is the pointer to ref2
going to be stored? On the stack: yes. But where on the stack? In the same memory location that was being 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 silly to simply 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 silly because ref1
isn't needed anymore.
That's why ref1
is eligible for garbage collection: there are no longer any references to it.