Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about Garbage Collection in Java

Suppose I have a doubly linked list. I create it as such:

MyList list = new MyList();

Then I add some nodes, use it and afterwards decide to throw away the old list like this:

list = new MyList();

Since I just created a new list, the nodes inside the old memory area are still pointing to each other. Does that mean the region with the old nodes won't get garbage collected? Do I need to make each node point to null so they're GC'd?

like image 812
captain poop Avatar asked Aug 17 '10 19:08

captain poop


1 Answers

No, you don't. The Java GC handles cyclic references just fine.

Conceptually, each time the GC runs, it looks at all the "live" root references in the system:

  • Local variables in every stack frame
  • "this" references in every instance method stack frame
  • Effectively, all static variables (In fact these are really referenced by Class objects, which are in turn referenced by ClassLoaders, but lets ignore that for the moment.)

With those "known live" objects, it examines the fields within them, adding to the list. It recurses down into those referenced objects, and so on, until it's found every live object in the system. It then garbage collects everything that it hasn't deemed to be live.

Your cyclically referenced nodes refer to each other, but no live object refers to them, so they're eligible for garbage collection.

Note that this is a grossly simplified summary of how a garbage collector conceptually works. In reality they're hugely complicated, with generations, compaction, concurrency issues and the like.

like image 96
Jon Skeet Avatar answered Nov 07 '22 20:11

Jon Skeet