How does Garbage Collection identify orphaned objects?

stefan.at.wpf :

Given a memory state like this:

(1) GC root -> A
(2) GC root -> B
(3) B -> GC root

where "->" means "has a reference to". Now imagine one removes the references from GC root to A and B. I know that A will be garbaged collected, as it's not reachable anymore.

But what about B? It's not reachable from the GC root, but it has a reference to the GC root, which is still alive. Is B now garbage collected or not? Or in other words: for finding orphaned objects, is the analysis only done in one direction, from GC root to other objects?

Louis :

The basic strategy used for garbage collection is to determine whether or not the data on the heap is reachable from the stack. If it is not, free its memory.

You can visualise this as so

STACK  *** HEAP *** HEAP *** STACK
GC root.  -> A      -> b   -> GC root

So if you remove A you still have B reaching the stack but the garbage collector never reaches B and removes it (it only traverses from left to right/from stack to heap). It does not matter that the stack can be reached from the heap in your example B -> root GC. Only that the heap data can not be reached from the stack.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=370542&siteId=1