Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage collection of circular referenced object

Lets say I have 2 objects - object A and object B. Object A references Object B and object B references Object A.

  1. If Both Object A & Object B are out of ref of the code - how does Garbage collector know that it can be collected.
  2. How does Garbage collector deduce that any object is out of scope / ready for garbage collection?
  3. What about if Object A is not ref by our code but can still be independent. E.g. if it is a Form class then it can run on its own even if Object A is reinitialized to a new instance or specified null.
like image 266
Alag20 Avatar asked May 16 '13 18:05

Alag20


1 Answers

  1. The GC doesn't pick an object and look to see if anything references it; keeping it if it does. The GC has a collection of every object that it knows is "alive". This collection starts out as all static variables, all variables on the stack, and a few other special cases. It then goes through each of those "alive" objects and sees what objects they reference. Each referenced object is itself marked as "alive" since it means that it is somehow reachable by another alive object. It repeats this process until no new objects are discovered. Anything that wasn't marked as alive is then known to be unreachable. As you can tell, since you have never inspected what any given "dead" object references, whether or not there is a circular reference isn't relevant.

  2. See #1.

  3. Well, in most of these cases it is actually referenced somewhere; in the case of a form, for example, you have Application.OpenForms referencing any open forms. Similar constructs often exist for objects such as these. In rare cases with objects such as timers they are explicitly told by the GC to not be collected. Such situations are very rare and you generally don't need to worry about them.

like image 98
Servy Avatar answered Sep 18 '22 13:09

Servy