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.
Does Java GC collect objects that lost its reference, but its variables still have reference?
So let's say I have SomeObject:
public class SomeObject {
public ObjectVar var;
public SomeObject() {
var = new ObjectVar();
}
}
And my code:
SomeObject obj1 = new SomeObject();
SomeObject obj2 = new SomeObject();
obj2.var = obj1.var;
obj1 = null;
So obj1's var has reference, but obj1 no longer has any reference. So, will the GC destroy obj1, but keep var alive? (I'm assuming so; just wanted to make sure). Thanks!
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.
Yes of course.
Remember, what you store in the var
field is actually reference to the object, not the object itself. So when GC collects obj1
, the var
object is untouched (must not be touched), especially since it has a reference from obj2
, which is still alive and well..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With