Kuba
Kuba

Reputation: 3056

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?

Upvotes: 7

Views: 1161

Answers (4)

vegemite4me
vegemite4me

Reputation: 6856

@Kuba Do you mean: can the instance of class B in the field b of instance a of class A be garbage collected? No. Not while a is not null as the b is referenced by a.

Upvotes: 1

Kuba
Kuba

Reputation: 3056

The standard compiler is not that 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 out of memory exception after a very small number of loops, so the answer to the original question is definitely no.

Upvotes: 1

axtavt
axtavt

Reputation: 242686

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

Upvotes: 7

dteoh
dteoh

Reputation: 5922

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

Upvotes: 1

Related Questions