简体   繁体   中英

Will these LinkedList nodes be eligible for garbage collection?

I am implementing my own LinkedList . Right now, I'm on the clear() function which removes all of the elements from the list.

Here is my code so far:

public class LinkedList<E> {
    // the first element of this LinkedList
    private Node start;

    // the last element of this LinkedList
    private Node end;

    // the number of elements that constitute this LinkedList
    private int length;

    private class Node {
        private Node last;
        private Node next;

        private E data;

        // each Node has a reference to the previous Node and
        // the next Node. The first element of the LinkedList
        // will have a null reference to the previous element
        // and the last element will have a null reference to
        // the next element. Each Node stores a piece of data
        // in the data variable.
    }

    public void clear() {
        start = null;
        end = null;

        length = 0;
    }

    // other methods omitted
}

In the clear() function, I set the start and end references to null . I am unsure how this will affect the nodes in the middle of the linked list (or even the start and end nodes).

If I have four nodes (or more) in my LinkedList , the middle two (or more) will point to each other. Once I set start and end to null , my code doesn't have any references to those objects anymore, but they have references to each other.

Will these middle nodes, or even the start and end nodes, be eligible for garbage collection or not, and why?

Bonus question: how could I figure this out experimentally?

Seems to me like you are worrying about the wrong thing here. GC will track all roots and clear children for them also. For you example this would mean that as soon as LinkedList is not used by active Threads, it will be eligible for Garbage Collection, even if children will point to some real data (Nodes in your case). What is the use of having an Object that is not needed anymore even if it relates itself to some data?

 LinkedList
    |   |

Node1  Node2

if LinkedList is Garbage Collected, so will the Nodes, you do not have to worry about this. Thus your clear method has to reset the LinkedList to a default, empty one and not worry about GC.

PS You might want to read how GC works, at least to understand roots.

Do not set null to the objects explicitly ... you create linked list object in some scope and when the scope is over it(along with nodes) is eligible to be garbage collected.

If its a web application write finalize() to log a message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM