I\'ve read through some of the Java garbage collection guides online, but I\'m still a bit unclear and wanted to make sure so that I don\'t have memory leaks in my code.
Simply put, if an object is still reachable by a path of references, it is guaranteed to survive collection. If there is no such path, the object can no longer be accessed, and may safely be collected.
After the first two lines, the memory looks like this:
o1 --> SomeObj#1 --> ObjectVar#1
o2 --> SomeObj#2 --> ObjectVar#2
All 4 objects can be reached, if a garbage collection were to occur at this time, none of them would be collected.
After the 3rd line, it looks like this:
o1 --> SomeObj#1 --> ObjectVar#1
^
o2 --> SomeObj#2 ----- ObjectVar#2
Now, only 3 objects can be reached; the garbage collector may remove ObjectVar#2.
After the 4th line, it looks like this:
o1 SomeObj#1 --> ObjectVar#1
^
o2 --> SomeObj#2 ----- ObjectVar#2
Only two objects are still reachable; the garbage collector may remove SomeObj#1 and ObjectVar#2, but must keep SomeObj#2 and ObjectVar#1.