Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage collection of private fields

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?

like image 351
Kuba Avatar asked Sep 28 '12 08:09

Kuba


2 Answers

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

like image 143
axtavt Avatar answered Nov 16 '22 19:11

axtavt


No, because the main thread has a path to b through a.

like image 1
dteoh Avatar answered Nov 16 '22 18:11

dteoh