我正在做一些 Java 认证书中的练习。在有关垃圾收集的问题中,他们提供了以下代码:
class Test {
private Demo d;
void start() {
d = new Demo();
this.takeDemo(d);
}
void takeDemo(Demo demo) {
demo = null;
demo = new Demo();
}
}
问题是
When is the Demo object, created on line 4, eligible for garbage collection?
我会说它可以在指令 demo=null 之后收集;因为不再有对它的引用,但在他们给出的答案中是:
When the instance running this code is made eligible for garbage collection
我错过了什么?
最佳答案
Java is "pass-by-value" ,所以这条语句demo = null;
只影响takeDemo
中demo
的本地副本。它不会将 d
设置为 null
,因此只要封闭实例可访问,它就可以访问。
关于java - null 后 Java 中的垃圾收集器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14772524/