Open secured double linked list in Java

I am currently participating in the CS exam, and in my opinion the following question came: if I have a doubly linked list with two fields (one boss and a guard) and I want to clear the list (make it is empty). Is it enough to set the tail of the node as an element nextafter my head and vice versa ( previous- node of the tail of the head). Will garbage collection remove elements between the two (elements refer to each other, but external links in the node of this "block" do not exist?

To make this a little clearer: if I have this:
|HEAD| <--> |node_01| <--> | . . .| <--> |node_n| <--> |TAIL|

And I change the next/ previousnode of the head and tail to this:
|HEAD| <--> |Tail|

Will Java delete node_01 - node_n(note the single arrows):
|HEAD| <-- |node_01| <--> | . . . | <--> |node_n| --> |TAIL|

They all refer to each other, but there is no external link - I can not contact them. Or is it a memory leak?

+4
source share
1 answer

In your specific example, the GC will completely clear the list. This is due to the fact that they are not reachable from the graph to the root objects of the graph of the application object.

In the implementation, clear()you may notice that a value is also set for each object null, which means that any memory if any object refers to it. But in your case, you specifically said that this cannot happen.

Implementation clearfor reference:

/**
 * Removes all of the elements from this list.
 */
public void clear() {
    Entry<E> e = header.next;
    while (e != header) {
        Entry<E> next = e.next;
        e.next = e.previous = null;
        e.element = null;
        e = next;
    }
    header.next = header.previous = header;
    size = 0;
modCount++;
}
+1

Source: https://habr.com/ru/post/1626739/


All Articles