How many items will be eligible for garbage collection after the execution of & ldquo; M1 = null; M2 = null; & Rdquo;

advertisements

I am confused to understand after executing m1 = null; m2 = null;. How many objects will be eligible for garbage collection?

public class MyTest {
    MyTest m;

    void show() {
        System.out.println("Hello this is show method.");
    }

    public static void main(String args[]) {
        MyTest m1 = new MyTest();
        MyTest m2 = new MyTest();
        MyTest m3 = new MyTest();
        m1.m = m2;
        m2.m = m3;
        m3.m = m1;
        m1 = null;
        m2 = null;
        // Question here: How many objects will be eligible for garbage collection?
    }
}


Zero.

Object reference diagram looks like this:

You can see that the reference is circular. A reference from main to m3 keeps the m3 object alive. In turn, m3 keeps alive m1, which keeps m2 from GC.

Note that if you set m3 to null, all three objects would become eligible for GC at once, despite circular references existing for each one of them. GC is smart enough to figure out that all references are coming from GC-eligible objects, and collect all three.