I'm looking at a method (delMin()) for deleting the small element in a heap. It sets the variable min
to equal the min value and then sets the value of min to null
to "avoid loitering and help with garbage collection." Could someone please explain how the JVM deals with this and why this is a good idea?
public Key delMin() {
if (isEmpty()) throw new NoSuchElementException("Priority queue underflow");
exch(1, N);
Key min = pq[N--];
sink(1);
pq[N+1] = null; // avoid loitering and help with garbage collection
if ((N > 0) && (N == (pq.length - 1) / 4)) resize(pq.length / 2);
assert isMinHeap();
return min;
}
and then sets the value of
min
to null
No it doesn't. It sets the final used element of the array to null
, so that the array no longer holds a reference to that object.
An object can only be garbage collected when there are no more strong references to it. You don't want the heap to hold onto a reference to an object that is no longer logically part of the heap, as that could end up being the last strong reference to the object.
In general, when removing an element from a collection, you need to make sure you no longer have a reference to the object in the collection - this is just a specific example of that rule.
See more on this question at Stackoverflow