Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Beginning Java and the fly likes How GC works with double linked list Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How GC works with double linked list" Watch "How GC works with double linked list" New topic

How GC works with double linked list

Rakoczi Markus

Joined: Mar 13, 2012
Posts: 13

my question is about GC.
Suppose I have an acyclic double linked list like: Start<->A<->B<->C<-> ... <->NULL. If I set Start->Null, will be the rest of the list eligible for garbage collection or not?
What happens if I have a circular linked list? Should I set each object next and prev to null to be eligible for garbage collection?

Steve Luke

Joined: Jan 28, 2003
Posts: 4181

As long as there are no external links to the nodes, then just setting the start to null should be okay. It may take more than one pass of the GC to collect all nodes, or it may collect them all in the same pass, depending on the implementation. But as long as there is no reachable reference to the Object, that Object is eligible for collection, regardless of the length of the 'unreachable' reference chain there might be.

Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

And to be "reachable" doesn't just mean that there exists some reference somewhere that points to it. It has to be reachable from code that's on the stack. Java's GC doesn't use reference counting, so being an "island" of A <--> B both pointing to each other does not prevent A and B from being GCed.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: How GC works with double linked list
jQuery in Action, 3rd edition