It is not about what is within which object. The GC will just swipe through all objects and check if it is reachable. finalize()
method will be executed only when the GC determines that an Object is unreachable.
public class TryThreads {
B b = new B();
@Override
protected void finalize() throws Throwable {
System.out.println("TryThreads finalizing..");
}
public static void main(String[] args) {
TryThreads t = new TryThreads();
t = null;
System.gc();
System.runFinalization();
}
}
class B {
String s = new String("hello");
@Override
protected void finalize() throws Throwable {
System.out.println("B finalizing");
}
}
O/P :
B finalizing
TryThreads finalizing..
Now, if b
of the TryThread
instance t had a Strong reference.
public class TryThreads {
B b = new B();
@Override
protected void finalize() throws Throwable {
System.out.println("TryThreads finalizing..");
}
public static void main(String[] args) {
TryThreads t = new TryThreads();
B b = t.b; // keeping a reference of b within t. only t will be collected, not b.
t = null;
System.gc();
System.runFinalization();
}
}
class B {
String s = new String("hello");
@Override
protected void finalize() throws Throwable {
System.out.println("B finalizing");
}
}
O/P :
TryThreads finalizing..