简体   繁体   中英

Is object eligible for garbage collection after “obj = null”?

I know System.gc() is not guaranteed to cause GC, but theoretically, in the following code, will the object obj be eligible for garbage collection?

public class Demo {

    public static void main(String[] args) throws Exception {
        SomeClass obj = new SomeClass();
        ArrayList list = new ArrayList();
        list.add(obj);
        obj = null;
        System.gc();
    }

}

class SomeClass {
    protected void finalize() {
        System.out.println("Called");
    }
}

At the point where you call System.gc() the SomeClass instance you created is not eligible for garbage collection because it is still referred to by the list object, ie it is still reachable .

However, as soon as this method returns list goes out of scope, so obj will then become eligible for garbage collection (as will list ).

Simply setting the reference obj to null does not, by itself, make the object referred to eligible for garbage collection. An object is only eligible if there are no references to it from the graph of visible objects.

will the object obj be eligible for garbage collection?

Only those objects are garbage collected who don't have even one reference to reach them. (except the cyclic connectivity)

In you code, there are two reference that are pointing to new SomeClass();

  1. obj
  2. zeroth index of list

You put obj = null , ie it's not pointing to that object anymore. But, still there exists another reference in list which can be used to access that object.

Hence the object will be eligible for GC only when main returns. ie you can't see the output of finalize method even if it got called. (not sure if JVM still calls it)

不,因为该对象实际存在于列表中。

You as Java programmer can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size

When a Java program started Java Virtual Machine gets some memory from Operating System. Java Virtual Machine or JVM uses this memory for all its need and part of this memory is call java heap memory.

Heap in Java generally located at bottom of address space and move upwards. whenever we create object using new operator or by any another means object is allocated memory from Heap and When object dies or garbage collected ,memory goes back to Heap space in Java

EDIT :

will the object obj be eligible for garbage collection?

No, because the object is still in the ArrayList.

同意,只要它在列表中,它就不会被垃圾收集。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM