When is an item eligible for garbage collection?

advertisements

This question already has an answer here:

  • Understanding garbage collection in .NET 3 answers

In the book C# 5.0 in a nutshell by Joseph Albahari I found this

where it says as soon as you pass the line of code where a variable is last used, the object referenced by it is eligible for garbage collection (That is if no other variable holds a reference to that object).

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. My understanding is, until the method returns, the variable stays on the stack. Which means any object referenced by it is alive until the method returns.

Is this an error in the book or does java and .net garbage collection work differently?


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.