class CardBoard {
Short story = 200;
CardBoard go(CardBoard cb){
cb = null;
return cb;
}
public static void main(String[] args){
CardBoard c1 = new CardBoard();
CardBoard c2 = new CardBoard();
CardBoard c3 = c1.go(c2);
c1 = null;
// When this line is reached, what is eligible for the GC.
}
}
有人可以解释一下这里发生了什么吗?我了解,c1
并且Short
有资格获得垃圾收集器。但是发生了什么c2
,为什么还不c3
可用呢?我可能会在这里监督一些事情,但是我很乐意为您提供帮助我解决该主题的各种意见。我的OCA考试是下周,但我仍然遇到这类问题。
编辑:对符合GC条件的评论。
可视化所涉及的对象将有所帮助。在main中的第一条语句之后,我们有:
+-----------+ +-------+
| CardBoard | ---> | Short |
c1 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
在main中的第二个语句之后,我们有:
+-----------+ +-------+
| CardBoard | ---> | Short |
c1 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
+-----------+ +-------+
| CardBoard | ---> | Short |
c2 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
(理论上,两个CardBoard也可能共享Short
对象,Javadoc ofShort.valueOf
表示:
此方法将始终缓存-128至127(包括)范围内的值,并且可能缓存该范围之外的其他值。
但是,JDK实现仅在-128到127范围内进行缓存,因此我们将假定继续进行)
进入go()方法后,我们将:
+-----------+ +-------+
| CardBoard | ---> | Short |
c1 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
+-----------+ +-------+
| CardBoard | ---> | Short |
c2 ----> |-----------| / |-------|
--> | story | / | 200 |
/ +-----------+ +-------+
/
/
cb
在离开go()之前,我们有:
+-----------+ +-------+
| CardBoard | ---> | Short |
c1 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
+-----------+ +-------+
| CardBoard | ---> | Short |
c2 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
cb --x
在main的第三个语句之后,我们有:
+-----------+ +-------+
| CardBoard | ---> | Short |
c1 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
+-----------+ +-------+
| CardBoard | ---> | Short |
c2 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
c3 --x
在离开main()之前,我们有:
+-----------+ +-------+
| CardBoard | ---> | Short |
c1 -x |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
+-----------+ +-------+
| CardBoard | ---> | Short |
c2 ----> |-----------| / |-------|
| story | / | 200 |
+-----------+ +-------+
c3 -x
我们可以看到,在分配的4个对象中,有2个仍可访问,有2个有资格进行收集。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句