Let's break this down line by line:
CardBoard c1 = new CardBoard();
We now have two objects, the CardBoard
c1
points at and the Short
c1.story
. Neither is available for GC as c1
points at the CardBoard
and the story
variable of the CardBoard
points at the Short
...
CardBoard c2 = new CardBoard();
Similar to above, we now have four objects, none of which are available for GC.
CardBoard c3 = c1.go(c2);
We invoke the method go on the CardBoard pointed at by c1
, passing the value of c2
which is a reference to a CardBoard
Object. We null the parameter, but Java is pass by value meaning that the c2
variable itself is unaffected. We then return the nulled parameter. c3
is null
, c1
and c2
are unaffected. We still have 4 objects, none of which can be GC'd.
c1 = null;
We null c1
. The CardBoard
object which c1
previously pointed at now has nothing pointing to it, and it can be GC'd. Because the story
variable inside that CardBoard
object is the only thing pointing at the Short
, and because that CardBoard
object is eligible for GC, the Short
also becomes eligible for GC. This gives us 4 objects, 2 of which can be GC'd. The objects eligible for GC are the ones formerly referenced by c1
and c1.story
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…