How does Garbage Collection in Java work?

2019-03-18 13:12发布

问题:

I was wondering how the garbage collector in Java deals with the following situation.

Object A has a reference to Object B and Object B has a reference to Object C. The main program has a reference to Object A. So you can use Object B trough Object A, and Object C trough Object B trough Object A.

What happens to Object B and Object C, if the link between Object A and Object B is set to null?

Should Object B and Object C now been collected by the Garbage Collector? I mean there is still a connection between Object B and Object C.

回答1:

Should Object B and Object C now been collected by the Garbage Collector?

Yes. Well, they are candidates for collection because there's no way to reach Object B and C through the root that is A.



回答2:

Yes, B and C are eligible for garbage collection, if they can't be reached from any GC root (GC roots are usually all Threads and all references on the stack).



回答3:

You can't count on the garbage collector to work at a specific time,since its behavior is unpredictable,all you can say is that objects B and C are only eligible for garbage collection



回答4:

As usual, this article is a must-read for whoever wants to understand what garbage collection does. It is well-written and has explanatory drawings.



回答5:

In fact, garbage collection in java is a very sophisticated thing, far more than in Ruby interpreter, as an example.

Anyway, the theoretical basis is the same.

The GC identifies objects graphs that are no more reachable by program code (that's to say they have no more reference in active code). When talking about object graph, I precisely talk about B->C object graph. once it is unreachable, it can be GC'ed, but you can't tell when it will be, due to the GC trying to optimize as much as possible its work to avoid slowing the application down.



回答6:

B and C are eligable for garbage collection because you can't access them any more. With the unpredicatbility of the garbage collector all we know is they are quite likely to get collected at some point in the future.



回答7:

I think the logic is different. If the object is not accessible from a thread then it can be collected.



回答8:

If there is no reference to object, then it will be suitable for GC to proceed



回答9:

B has no reference to it so it will be garbage collected first, then it will understand that C has no reference to it, so C will be garbage collected. It is for illustration, Jvm is smart enough to scoop them in one sweep.