Will an element be garbage collected if there is a

2020-04-02 06:53发布

I.e., in

class A {
    public String s;
}

and

A a1 = new A();
a1.s = "bla";
A a2 = new A();
a2.s = a1.s;
a1 = null;

will a1 be garbage collected or is the reference to a1.s permitting it from being collected (and I should rather do a deep copy, a2.s = new String(a1.s))?

Thanks a lot in advance!

4条回答
Anthone
2楼-- · 2020-04-02 07:29

If an object holds a reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.

See this link for further information.

查看更多
贪生不怕死
3楼-- · 2020-04-02 07:42

Here you are creating two references of Object A like a1 and a2.

First, you are assigning value of a1 to a2.So after setting value to a2, a1 is allowed for GC. But there will be no change in reference a2.

You can also check this blog for Garbage Collection:

查看更多
ゆ 、 Hurt°
4楼-- · 2020-04-02 07:44

Since A has only a reference to s, a2.s pointing to a1.s would not affect a1's garbage collection.

i.e a1 is eligible for GC, but the object referred to by a2.s (or a1.s) will not be eligible for GC.

查看更多
萌系小妹纸
5楼-- · 2020-04-02 07:51

The object A1 is eligible for GC as now it is set to be null. But as String "bla" in not available for GC because it also referred by a2.s. So only a1 object is available for GC.

If this is the case

A a1 = new A();
a1.s = "bla";
A a2 = new A();
a1 = null;

then both a1 object and "bla" is available for GC. Because all references of "bla" is removed but now the case is

a2.s = a1.s;

a2 is refering to same string "bla". So string is available in stringpool not for GC

查看更多
登录 后发表回答