Eligible variables for garbage collection in Java

早过忘川 提交于 2019-12-04 05:54:02

Lets call Icelandic() on line 11 IceA, line 12 IceB, and so forth.

After creation

i1 = IceA
i2 = IceB
i3 = IceC

After i3 = i1

i1 = IceA
i2 = IceB
i3 = IceA

After i1 = i2

i1 = IceB
i2 = IceB
i3 = IceA

After i2 = null

i1 = IceB
i2 = null
i3 = IceA

After i3 = i1

i1 = IceB
i2 = null
i3 = IceB

So only the Icelandic() created on line 12 remains. Now, each Icelandic() has a Long weight, so IceA and IceC are now unreferenced, meaning 4 objects (IceA, IceA.weight, IceC, IceC.weight) are available for GC.


Other issues:

  1. args is still args, they are not counting going out of scope in this question
  2. Long weight is not declared statically, so each instance of the class has a weight object.

Let's call the first Icelandic object that is created "A", the second one "B", and the third one "C". After line 12, they are referenced by i1, i2, and i3, respectively.

Now, we do:

i3 = i1; // object "C" is no longer referenced, object "A" is now referenced by i1 and i3
i1 = i2; // object "A" is just referenced by i3, object "B" is referenced by i1 and i2
i2 = null; // object "B" is just referenced by i1 now
i3 = i1; // object "B" is referenced by i1 and i3, object "A" is no longer referenced

So, objects "A" and "C" are no longer referenced, and they along with their "weight" are eligible for garbage collection, so four objects total.

You will have 4 objects in the system, 3 Icelandic instances and 1 Long instance.

When you assign constant object to some variable, compiler uses kind of private static final Long long1200 = Long.valueOf(1200L); object that is shared by all weight instances.

Primitive type wrappers are immutable, so it is safe to do this optimization.

EDIT: probably I am wrong, because this would work this way if we referenced the same constant several times here, which is not the case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!