Sergey Chepurnov
Sergey Chepurnov

Reputation: 1447

available objects for System.gc()

Basically, I try to take a test and stuck with question about the garbage collector:

How many objects available for System.gc() in the following code snippet:

public class WorkGC {
    static class StaticNestedClass  {
        private String name;
        public StaticNestedClass(String name) {
        this.name = name;
        }
    }

    public static void main(String[] args) {
        StaticNestedClass n1 = new StaticNestedClass("n1");
        StaticNestedClass n2 = new StaticNestedClass("n2");
        Collection list = new ArrayList();
        list.add(n1);
        StaticNestedClass[] arr = new StaticNestedClass[2];
        arr[0] = n2;
        n2 = n1;
        clear(arr);
        n1 = null;
        n2 = null;
        System.gc();
       //the rest of the code
    }

    private static void clear(StaticNestedClass[] arr) {
        arr = null;
    }
}

I think 2 objects are available:

1)arr – after clear(arr)

2)n2 – after n2=null

I don't sure that arr – is one object, may be arr is a series of objects. Also, I'm not sure about instances of StaticNestedClass, it is static and locates in a PermGen – not in the Heap as typical objects. Does GC works in PermGen as well as in the Heap?

Upvotes: 0

Views: 47

Answers (1)

TheLostMind
TheLostMind

Reputation: 36304

I think : `No Object is ready for GC. I assume this would be the scenario:

public static void main(String[] args) {
        StaticNestedClass n1 = new StaticNestedClass("n1"); //  1st object created 
        StaticNestedClass n2 = new StaticNestedClass("n2");  // 2nd object created 
        Collection list = new ArrayList(); // 3rd object
        list.add(n1); // n1 has a strong reference, so n1 is not ready for GC.
        StaticNestedClass[] arr = new StaticNestedClass[2];// 4th object created
        arr[0] = n2; //n2 has strong reference, so, even n2 is not ready.
        n2 = n1; // both n1 and n2 point to same object as that of n1. but arr[0] still references n2. 
        clear(arr); // you are passing references by value. SO, this has absolutely no effect on GC.
        n1 = null;// Object pointed to by n1 is still being referenced by n2
        n2 = null; //Object pointed to by n1 has a reference in the list.
        System.gc();
       //the rest of the code
    }


    private static void clear(StaticNestedClass[] arr) {
        arr = null;
    }

So, basically No Object is ready for GC.

Upvotes: 1

Related Questions