I have read that in Java, GC (Garbage Collection) will clean up objects that are not referenced in the Heap memory.
I am not sure how to test or not sure if, after line 3, the variables person, room (in the voidTest function) can be called as having no reference.
Does anyone know how to test or could explain further for me?
Thank you!
class Main{
public static void main(String[] args) {
voidTest();
// is Gc clean room and person variable in void Test ?
}
public static void voidTest(){
Person person = new Person();
Room room = new Room();
room.person = person;
person.room = room;
}
}
class Room{
public int id;
public Person person;
}
class Person{
public String name;
public Room roon;
}
>Solution :
Finalizers aren’t a great idea and they are being removed from the language. But they are still available, so that allows you to do some cheap and easy GC testing. Calling System.gc() manually allows you to see the result of a garbage collection.
public class GCTesting {
public static void main( String[] args ) {
test();
System.gc();
}
private static void test() {
new GCTesting();
}
@Override
protected void finalize() {
System.out.println( "Bye!" );
}
}