Does Java GC destroy objects if instance variables still have reference?

后端 未结 4 1915
天命终不由人
天命终不由人 2021-02-07 08:51

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.

4条回答
  •  余生分开走
    2021-02-07 09:27

    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.

提交回复
热议问题