Private waste collection

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 object B be garbage collected after creating object A?

+5
source share
4 answers

I think not, because this field can still be obtained through reflection (using setAccessible(true)).

Theoretically, the compiler can prove that this field will never be available, and it will make it Bsuitable for garbage collection (from JLS 12.6.1 Implementation of completion ):

, . , , , , , . , , , .

, JVM -

+6

@Kuba : B B a a ? . a null, B a.

+1

No, because the main thread has a path to bthrough a.

+1
source

The standard compiler is not so smart.

class A
{
    private Object[] array;

    public A()
    {
        array = new Object[10000000];
    }
}

public static void main(String[] args)
{
    LinkedList<A> list = new LinkedList<A>();
    while (true)
    {
        list.add(new A());
    }
}

This code throws an exception after a very small number of loops, so there is definitely no answer to the original question.

0
source

All Articles