Reputation: 581
So I came across some confusing code like this.
public class Class1 {
private Class2 class2 = new Class2(this);
public void dispose() {
if (class2 != null) {
class2.dispose();
}
if (class2 != null) {
class2.dispose();
class2 = null;
}
}
}
public class Class2 {
private Class1 class1;
private Class3 class3 = new Class3();
public Class2(Class1 class1) {
this.class1 = class1;
}
public void dispose() {
if (class3 != null) {
class3 = null;
}
class1 = null;
}
}
This is just an extract of what is important to this question from the actual classes. I know the way this code is written is not correct but it is like this.
Instance of Class1 is passed on to the constructor of Class2 & kept as a class variable, while the instance of Class1 keeps the instance of Class2 as a class variable.
When dispose() method is called in Class1, it calls the dispose method in Class2, and in the dispose method of Class2 it assigns null to the Class1 variable it has kept there.
This code does not produce an error and executes all the lines in the dispose() method of Class1.
Aren't the instance of Class1 that is being nullified by the dispose method in Class2, and the instance of Class1 calling the dispose() on Class2, the same?
Upvotes: 0
Views: 110
Reputation: 140427
It sounds like you don't understand the difference between the concept of objects on the heap and references "pointing" to objects. In your example, there are two objects that get created, as there are two calls to new whatever()
.
You can have multiple references pointing to those two objects, but setting a reference to null
does not "delete" (or dispose) the actual object on the heap.
Meaning: the objects continue to exist, as long as the garbage collector considers them "alive". As the given example is incomplete, it is not possible to determine the overall "alive" state of the different objects. Well, the Class2
instance is no longer referenced, so that one is eligible to be collected by the garbage collector. But we don't know how you created the actual instance of Class1
that your test would need.
Upvotes: 4