1

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;
}
  • Possible duplicate of [Java garbage collector - When does it collect?](http://stackoverflow.com/questions/1582209/java-garbage-collector-when-does-it-collect) – Turing85 May 22 '16 at 07:50

3 Answers3

1

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

The space allocated to an object is reclaimed by the garbage collector once there are no references to that object. In the code you provided, setting min only helps garbage collection if there are no references to the underlying object

Francis
  • 3
  • 3
0

The person who wrote that comment is being "cute". The real purpose of the assignment is to avoid a (Java) memory leak.

The GC doesn't realize that references in pq beyond pq[N] are "dead"; i.e. they won't ever be used again by the priority queue implementation. If the code didn't assign null to that slot, then those dead references could prevent the GC from collecting the corresponding objects.

Could someone please explain how the JVM deals with this ...

The JVM is not actually dealing with this. The code is doing the "dealing with".

... and why this is a good idea?

Because it avoids a memory leak, which (in the worst case) could cause an application using this code to fill up the heap and crash.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216