Calls new Object (); make the object created by the first call eligible for garbage collection twice?

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 is the method called doSomething()

after which the line Object

created on line 5 is made available for garbage collection?

The correct answer is line 8.

Why? I think it should be line 7, because new initiates a new Object

one and then gets assigned o

, causing the Object

one created on line 5 to lose its reference (then become available to the GC). Am I wrong?

+3


source to share


1 answer


The correct answer is line 8. Why?



You are confusing o

local with doSomething()

with o

, which is at the class level. Even though line 7 sets the doSomething () version o

to some other reference, you still have a class o

-level class that was set using the method doSomethingElse()

. You have to provide this reference to make it GC acceptable and this only happens when the method is called on line 8.

+4


source







All Articles