简体   繁体   中英

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?

The correct answer is Line 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). Am I wrong?

The correct answer is Line 8. Why is that?

You are confusing the o local to doSomething() with the o that is at the class level. 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. You have to null that reference to make it GC eligible, and that only happens by the method call on line 8.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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