Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Garbage Collection in Java work?

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.

like image 291
JordyOnrust Avatar asked Mar 12 '10 09:03

JordyOnrust


2 Answers

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.

like image 50
bruno conde Avatar answered Sep 29 '22 23:09

bruno conde


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).

like image 41
Joachim Sauer Avatar answered Sep 29 '22 22:09

Joachim Sauer