class ClassA {
ClassB mem1 = new ClassB();
ClassB mem2 = new ClassB();
}
class ClassB {
}
public class Sample {
public static void main(String[] args)
You have 3 instances of classes: One of ClassA
(I call it classA_1
) and two of ClassB
(classB_1
, classB_2
). Now look at all the reference paths that exist to those 3 instances.
Before obj1 = null
it looks smth. like this:
classA_1 <- Sample.main.obj1
classB_1 <- classA_1.mem1 <- Sample.main.obj1
classB_1 <- Sample.main.obj2
classB_2 <- classA_1.mem2 <- Sample.main.obj1
After obj1 = null
it looks like this, where no ref.
means, it is eligible for garbage collection, because it has no reference pointing to it.
classA_1 <- no ref.
classB_1 <- classA_1.mem1 <- no ref.
classB_1 <- Sample.main.obj2
classB_2 <- classA_1.mem2 <- no ref.
The only path that remains is this: classB_1 <- Sample.main.obj2
. There a no paths with valid references to objects classB_2
and classA_1
. So these objects can be collected.
Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.
Java Garbage Collection Basics
In this context, when obj1 = null;
is processed there are no references to the object of type ClassA
to which it points, and so it is eligable for garbage collection. The ClassB
object, mem1
however still has a reference in the form of obj2
and so is kept at least until the line obj2 = null;
is executed.
After obj1
is no longer referenced, it becomes eligible for garbage collection. mem1
still has a reference, so if java were to garbage-collect at this point, obj1
and mem2
it points too would be freed, but mem1
would remain untouched as obj2
still points to it.
Of course, after obj2 = null
, it can also be collected.