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 B
eligible for garbage collection (from JLS 12.6.1 Implementing Finalization):
A reachable object is any object that can be accessed in any potential continuing computation from any live thread. Optimizing transformations of a program can be designed that reduce the number of objects that are reachable to be less than those which would naively be considered reachable. For example, a compiler or code generator may choose to set a variable or parameter that will no longer be used to null to cause the storage for such an object to be potentially reclaimable sooner.
But I don't think that in practice compilers and JVMs are that smart
No, because the main thread has a path to b
through a
.
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