Abhishek Singh
Abhishek Singh

Reputation: 9765

Java Garbage collection eligibility

I am preparing for OCJP exam. I am giving a mock test. Here is a code snippet.

public class GC {
    private Object o;

    private void doSomethingElse(Object obj) {
        o = obj;
    }

    public void doSomething() {
        Object obj = new Object(); // Line 5
        doSomethingElse(obj);      // Line 6
        obj = new Object();        // Line 7
        doSomethingElse(null);     // Line 8
        obj = null;                // Line 9
    }
}

When the doSomething method is called, after which line does the Object obj become available for garbage collection?

I know the answer is Line 9 , however according to the exam simulator it is line 8 ? I am not sure who is right ?

Upvotes: 1

Views: 79

Answers (2)

Aaron Digulla
Aaron Digulla

Reputation: 328744

The simulator is right. In line 7, you overwrite the local hard reference to the instance, so the code in line 9 makes the second Object eligible for GC. The first one becomes eligible with line 8.

Longer explanation:

Line 5: create inst1 and assign to obj
Line 6: put inst1 into this.o. There are now two hard references to inst1
Line 7: create inst2 and assign to obj. this.o still points to inst1
Line 8: Clear reference this.o, make inst1 available for GC
Line 9: Clear reference obj, make inst2 available for GC

Upvotes: 6

Prasad
Prasad

Reputation: 90

The object created in line 5 gets eligible for garbage collection after line 8 and the one created in 7 gets eligible for garbage collection in line 9.

Upvotes: 1

Related Questions