Reputation: 3968
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");
}
}
Upvotes: 3
Views: 2227
Reputation: 13872
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();
You put obj = null
, i.e. 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. i.e. you can't see the output of finalize
method even if it got called. (not sure if JVM still calls it)
Upvotes: 4
Reputation: 48592
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.
Upvotes: 1
Reputation: 4202
Agreed, it won't be garbage collected as long as its there in the list.
Upvotes: -2
Reputation: 54286
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, i.e. 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.
Upvotes: 8