简体   繁体   English

调用new Object(); 两次使第一次调用创建的对象有资格进行垃圾回收?

[英]Does calling new Object( ); twice make the object created by first call eligible for garbage collection?

Given: 鉴于:

    1. public class GC {
    2.    private Object o;
    3.    private void doSomethingElse(Object obj) { o = obj; }
    4.    public void doSomething() {
    5.       Object o = new Object();
    6.       doSomethingElse(o);
    7.       o = new Object();
    8.       doSomethingElse(null);
    9.       o = null;
    10.   }
    11. }

When the doSomething() method is called, after which line does the Object created in line 5 becomes available for garbage collection? 当调用doSomething()方法时,在第5行中创建的Object可用于垃圾回收之后是哪一行?

The correct answer is Line 8. 正确答案是第8行。

Why is that? 这是为什么? I think it should be Line 7 because new will initiate a new Object and then assigned to o , which resulted in the Object created in Line 5 lose its reference (then become eligible for GC). 我认为它应该是第7行,因为new将启动一个新的Object然后分配给o ,这导致第5行中创建的Object失去其引用(然后才有资格获得GC)。 Am I wrong? 我错了吗?

The correct answer is Line 8. Why is that? 正确答案是第8行。为什么?

You are confusing the o local to doSomething() with the o that is at the class level. 你将doSomething()o局部与类级别的o混淆。 Even though line 7 sets the doSomething() version of o to some other reference, you still have the class-level o that was set through the doSomethingElse() method. 尽管第7行将doSomething()版本的o为其他引用,但仍然具有通过doSomethingElse()方法设置的类级别o You have to null that reference to make it GC eligible, and that only happens by the method call on line 8. 您必须将该引用置空以使其符合GC条件,并且仅通过第8行上的方法调用发生。

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

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