Garbage Collection and RemoveFirst from LinkedList

In the removeFirst lecture regarding LinkedList, Mosh says an interesting thing about Garbage Collection (GC), and I’m not sure I agree.
The example: Say you have a LinkedList with 10–>20–>30
You call removeFirst(), which should set first = first.next.
But Mosh says the Java GC will not be able to remove the initial first (10) from memory, because it still holds a reference to 20. And we need to remove that reference.
But I thought that GC is all about what REFERNECES an object, and not about what an object REFERENCES. If nothing references an object, it can be GC’d, right?
So in just setting first = first.next, you now no longer have any references to the original ‘first’, and so it should be GC’d. Or am I missing something fundamental about GC here?

2 Likes

This is such a good question, to which I do not have an answer.

Oracle defines garbage collection as follows, “Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.”

  10-->20-->30-->

So, I would think that by moving the first reference from 10 (first) to 20 (first.next) the garbage collector would be ready to collect the 10.

@cyborg I agree, first = first.next should be legit.