Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Garbage collection and Memory leak in Java

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!" );
   }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading