MBZ
MBZ

Reputation: 27632

GC collects referenced object after return from scope

I have a question about how GC works in Java. Consider the following code:

class C1 {
    ArrayList<int> myList = new ArrayList<int>();

    public void setList(ArrayList<int> l) {
         myList = l;
    }
}

func(C1 C) {
    ArrayList<int> l1 = new ArrayList<int>();
    l1.add(1);
    C.setList(l1);
}

main() {
    C1 C = new C1();
    func(C);
    ...
}

my question is: does GC releases 'l1' after func() returns or not?

Upvotes: 1

Views: 100

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200306

There is actually an optimization that HotSpot's JIT does, which is detecting the point at which a local var will no longer be accessed and clearing it at that moment. So the full answer to your question is "it might, but there is no guarantee". Recently I played with some code and measured the memory taken by a large array. Until I actually inserted array.hashCode() at te end of the method, I observed it was being released earlier.

Upvotes: 2

erickson
erickson

Reputation: 269897

No, it doesn't, because there's a root reference (stack variable C) which has a strong reference (myList), to the new ArrayList. After main() returns, then the C1 and the ArrayList are collectible, because the root reference disappears.

Upvotes: 5

Related Questions