简体   繁体   English

垃圾收集工作

[英]Garbage Collection's working

Here I have a Java doubt regarding the Garbage Collection: 在这里,我对垃圾收集有一个Java疑问:

protected class Robocop {
Integer weight = 200;

Robocop attent(Robocop rb) {
rb = null;
return rb;
}
public static void main(String[] args) {
System.out.println("indeed the solution is behind the corner);

Robocop rb1 = new Robocop();

Robocop rb2 = new Robocop();

Robocop rb3 = rb1.attent(rb2);

rb1 = null;

}
}

How many objects do you reckon are going to be eligible for GC? 您认为有多少个对象符合GC的条件?

My take on this, would be 4 object to be garbage collected rb3, rb1 and the related Integer wrapper instance variables. 我对此采取的,将4个对象作为垃圾收集rb3,rb1和相关的Integer包装器实例变量。

Inside your method you could as well just return null since you get a copy of reference as argument to your method, not the original reference itself. 在你的方法中你也可以返回null因为你得到一个引用的副本作为你的方法的参数,而不是原始的引用本身。 Thus, you cannot modify original reference inside of your method. 因此,您无法修改方法内部的原始引用。 You can only modify the object this reference refers to. 您只能修改此引用引用的对象。

Right at the end of main, 2 objects will be eligible for GC: one Robocop (with one Integer inside). 在main的末尾,2个对象将有资格用于GC:一个Robocop (内部有一个Integer )。

After main has finished, JVM will just shut down (in your case) and no GC will happen. 在main完成后,JVM将关闭(在您的情况下)并且不会发生GC。

It's probably best to try it with a profiler, which can show the exact number of objects at any given time. 最好用分析器进行尝试,分析器可以在任何给定时间显示对象的确切数量。 It looks like you have a typo in your code. 看起来您的代码中有拼写错误。 You probably meant Robocop rb3 = rb1.attent(r2); 你可能意味着Robocop rb3 = rb1.attent(r2); Assuming that this is what you meant, rb2 will be eligible for GC, and then rb1 will be eligible as well, since they point to null. 假设这是你的意思,rb2将有资格获得GC,然后rb1也符合条件,因为它们指向null。
So the answer is 2. 所以答案是2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM