The work of garbage collector in Java

Calling system What objects are available for garbage collection when gc()? Why?

public class GCTest {
    static class A {
        private String myName;
        public A(String myName) {
            this.myName = myName;
        }
    }

    public static void main(String[] args) {
        A a1 = new A("a1");
        A a2 = new A("a2");
        ArrayList list = new ArrayList();
        list.add(a1);
        A[] mas = new A[2];
        mas[0] = a2;
        a2 = a1;
        clear(mas);
        a1 = null;
        a2 = null;
        System.gc();
        // some code
        ...
    }

    private static void clear(A[] mas) {
        mas = null;
    }
}

If object = = null, does it become garbage?

I think A1, A2 and MAS are calling system GC () can be used for garbage collection because it is in a null state Or am I wrong?

Solution

First, your program variables will never be "available for garbage collection" GC only collects objects. Program variables are references to objects, not objects themselves (common terms that refer to Java variables confuse this.)

Second, objects referenced by A1, A2, or MAS are not GC Despite the fact that A1 and A2 have been set to null This is because references to these objects can still be accessed through lists or MAS Why can A2 referenced objects still be accessed through MAS even after clear () is called? Because you cannot change the value of the variable MAS in main () by passing the variable to the method clear() All you do in this method is to change the formal parameter (also known as MAS), which is a variable separate from the local variable in main () Java passes strictly by value However, when it comes to objects, a reference is always passed

In general, the rule is that an object will be GC only if it cannot be accessed directly or indirectly from any program variable

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>