This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
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

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
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 agree. Here's the link:
subject: How GC works with double linked list
It's not a secret anymore!