Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an object garbage if it is referenced only from garbage?

Suppose there is an object a of class A, which holds a reference to another object b of class B. And this is the only reference to b. So now, if all references to a is removed, then a is ready to GC. Does this mean that b is also ready to get garbage collected? because, though b has a reference ( inside a ), it is unreachable, because a is unreachable.

So how exactly does this scenario works? I mean the order of garbage collection.

like image 740
shar Avatar asked Jul 06 '13 17:07

shar


2 Answers

Java GC is smart enough to collect islands of isolated objects though they maybe pointing to each other. Hence, b also becomes eligible for garbage collection. The point to note here is that although you have a reference to b it's not live in the sense that it cannot be reached from your program's root.

like image 28
Ravi K Thapliyal Avatar answered Nov 15 '22 16:11

Ravi K Thapliyal


Once an object is unreachable from a root, it will be collected. See this question for an explanation of GC roots.

Entire subgraphs will be collected (as you describe) presuming no node within that subgraph may be reached.

Java (and .NET) use mark and sweep garbage collection which deals with this kind of problem.

Reference count-based systems (such as C++'s std::shared_ptr<T>) may fail in the case of circular dependencies that remain unreachable. This is not a problem for Java/.NET GC.

like image 183
Drew Noakes Avatar answered Nov 15 '22 16:11

Drew Noakes