shar
shar

Reputation: 2078

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.

Upvotes: 10

Views: 225

Answers (5)

Prasad Kharkar
Prasad Kharkar

Reputation: 13556

Even if the objects reference internally to each other, and they do not have a reachable reference from program, they will be eligible for GC. THere is a good explanation with diagrams here

http://www.thejavageek.com/2013/06/22/how-do-objects-become-eligible-for-garbage-collection/

Upvotes: 0

fastcodejava
fastcodejava

Reputation: 41097

That is exactly the point of GC. Since b is unreachable from main thread, it will be garbage collected. It is not just the count that matters.

Upvotes: -1

Bernd Elkemann
Bernd Elkemann

Reputation: 23550

It depends on the GC. A JVM can be told to use different GC's and typically uses 3 GC's as one (eden, copy, markcompact).

In any typical GC and in refcounting the situation you described is handled cleanly, both objs are collected. Think of it in 2 stages: first "a" gets noticed and collected then "b" gets noticed and collected. Again: the specific means of noticing depends on the GC.

Upvotes: 0

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

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.

Upvotes: 1

Drew Noakes
Drew Noakes

Reputation: 310907

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.

Upvotes: 13

Related Questions