Deleting a single linked list by just making head

2019-08-04 09:38发布

问题:

Why can't I just make head=null to delete the complete Linked list?

3 = head > 1 > 2 > 4 > null

By making head = null, JVM will take care of it.As head node is not referenced by any variable , it should be garbage collected.

What is wrong with this solution?

Note: I'm aware of the correct solution to delete the complete link list but I'm curious why I can't just make head=null to delete the complete linked list?

回答1:

Here's the code of java.util.LinkedList.clear(), verbatim:

public void clear() {
    // Clearing all of the links between nodes is "unnecessary", but:
    // - helps a generational GC if the discarded nodes inhabit
    //   more than one generation
    // - is sure to free memory even if there is a reachable Iterator
    for (Node<E> x = first; x != null; ) {
        Node<E> next = x.next;
        x.item = null;
        x.next = null;
        x.prev = null;
        x = next;
    }
    first = last = null;
    size = 0;
    modCount++;
}

The comment answers your question. It's unnecessary. But it can help the GC, and it can make more objects eligible to GC sooner if there is an Iterator that references one of the nodes: the referenced node still won't be eligible to GC, but all the nodes after and before the referenced node will be, since they're not referenced anymore.

Note that the developer chose to make the clear() method slower (O(n) instead of O(1)), to make the GC faster and reduce "memory leaks". You could do the inverse choice.

Also note that you might never call clear(), and just stop referencing an object of type LinkedList, leaving all the nodes linked together. The GC will collect all the nodes if none of them is reachable through a reference chain from a GC root. That's what happens 99% of the times you use a list.