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

后端 未结 4 1909
天命终不由人
天命终不由人 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:18

    Here is what is going to happen (see comments below)

    // obj1 and obj1.var get created
    SomeObject obj1 = new SomeObject();
    // obj2 and obj2.var get created
    SomeObject obj2 = new SomeObject();
    // old obj2.var becomes eligible for GC
    obj2.var = obj1.var;
    // obj1 becomes eligible for GC
    obj1 = null;
    

    In the end, two objects remain that do not get GCd - obj2 and the former obj1.var which is now referenced as obj2.var.

    Note: In a special case of ObjectVar class being a non-static inner class of SomeObject, keeping a reference to obj1.var would also keep obj1 around. This is because internally the SomeObject.ObjectVar class has a hidden variable of type SomeObject, which references the outer object of the inner class.

提交回复
热议问题