垃圾收集 - 为什么c3不适合在这个例子中收集(SCJP 6) [英] Garbage collection - why is c3 not eligible for collection in this example (SCJP 6)

查看:260
本文介绍了垃圾收集 - 为什么c3不适合在这个例子中收集(SCJP 6)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于:

  

来自SCJP 6预习书 - > class CardBoard {
Short story = 200;
CardBoard去(CardBoard cb){
cb = null;
return cb;

public static void main(String [] args){
CardBoard c1 = new CardBoard();
CardBoard c2 =新的CardBoard();
CardBoard c3 = c1.go(c2);
c1 = null;
//做东西
}
}

当// doStuff已达到,有多少对象符合GC要求?


A。 0



B。 1



C。 2



D。编辑失败



E。不可能知道

F。运行时抛出异常


正确的答案是C - 只有一个CardBoard对象(c1)符合条件,但它有一个



我的问题是为什么c3不符合收集条件?



我的想法是 -



c1.go(c2)将本地引用变量cb(它是c2的一个副本)设置为null,然后返回cb,它是分配给c3。我知道c2的引用变量本身不能在方法中修改,只能在它后面的对象中修改。但是,在我看来,引用变量cb的副本被设置为空并且被分配给c3。为什么c3在这个实例中没有设置为返回的空值?

解决方案

没有与c3相关的对象。它的值为空,所以没有任何收集。


Taken from SCJP 6 prep book -

Given:

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;
        // do Stuff
    }
}

When // doStuff is reached, how many objects are eligible for GC?

A. 0

B. 1

C. 2

D. Compilation fails

E. It is not possible to know

F. An exception is thrown at runtime

The correct answer is C - " Only one CardBoard object (c1) is eligible, but it has an associated Short wrapper object that is also eligible."

My question is why is c3 not eligible for collection?

My thoughts are -

c1.go(c2) sets the local reference variable, cb (which is a copy of c2), to null and then returns cb which is assigned to c3. I know that the reference variable for c2 itself cannot be modified in the method, only the object behind it. However it would appear to me that the copy of the reference variable, cb, is set to null and assigned to c3. Why is c3 not set to the returned null in this instance?

解决方案

There is no object related to c3. Its value is null, so there's nothing to collect.

这篇关于垃圾收集 - 为什么c3不适合在这个例子中收集(SCJP 6)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆