Given the code below.
class A {
private B b;
public A() {
b = new B();
}
}
class Main {
public static void main(String[] args) {
A a = new A(); // two objects are created (a and b)
// <-- is B object, referenced only by private a.b eligible for garbage collection?
keepAlive(a);
}
}
Can B object be garbage collected after the A object is created?
I think no, because this field still can be accessed via reflection (using
setAccessible(true)).Theoretically, compiler can prove that this field would never be accessed, and it would make
Beligible for garbage collection (from JLS 12.6.1 Implementing Finalization):But I don’t think that in practice compilers and JVMs are that smart