Eligible Object for Garbage Collection when all the references of that object explicitly assigning to Circular Link

Overview

JVM will reclaim the unused object from heap memory for future use.Unused Object means no longer referenced by any part of your program pointer to that object. To demonstrate unused object is reclaim by garbage collector by calling System.gc() function.System.gc() method provides just a "hint" to the JVM that garbage collection should run. But It is not guaranteed!!

Circular Nature

Object References is Circular Nature means initially Object is created on own memory address on heap memory and later more than one objects pointing to same memory address on heap memory.

Below Example - Garbage Collector will call when object references in circular nature occur

public class EligibleCircular {  
  protected void finalize(){
   System.out.println("Unused Object is reclaim by Garbage Collector:"+this);
  } 
  public static void main(String[] args) {
   EligibleCircular obj1 = new EligibleCircular();
   EligibleCircular obj2 = new EligibleCircular();  
   System.out.println("Before Assinging obj2 to obj1 object");
   System.out.println("obj1 = "+obj1);
   System.out.println("obj2 = "+obj2);
   obj1 = obj2;
   System.gc();
   System.out.println("After  Assinging obj2 to obj1 object");
   System.out.println("obj1 = "+obj1);
   System.out.println("obj2 = "+obj2);
  }
}

Output

Before Assinging obj2 to obj1 object
obj1 = EligibleCircular@1bab50a
obj2 = EligibleCircular@c3c749
After  Assinging obj2 to obj1 object
obj1 = EligibleCircular@c3c749
Unused Object is reclaim by Garbage Collector:EligibleCircular@1bab50a
obj2 = EligibleCircular@c3c749

Explanation

Above example System.gc() function is called after assigned obj2 to obj1.Both object is pointing the same address of obj2.Now obj1 memory address is Dangling pointer. So the obj1 is reclaimed and it is called the finalize method.

Note : Output Order may change based on System.gc() function calling the finalize method.

0 comments:

Post a Comment