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