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

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!!

Below Example - Garbage Collector is called before object assigning to null value

public class EligibleSetNull { 
  protected void finalize(){
    System.out.println("Unused Object is reclaim by Garbage Collector...");
  }
  public static void main(String[] args) {
    EligibleSetNull obj1 = new EligibleSetNull();  
    System.out.println("Before Setting Null to Object.");
    System.gc();
    obj1 = null;  
    System.out.println("After  Setting Null to Object.");
  }
}

Output

Before Setting Null to Object.
After  Setting Null to Object.

Explanation

Above example System.gc() function is called before setting the null value to object.So the object is not reclaimed and it is not called the finalize method.

Below Example - Garbage Collector is called After object assigning to null value

public class EligibleSetNull { 
  protected void finalize(){
    System.out.println("Unused Object is reclaim by Garbage Collector...");
  } 
  public static void main(String[] args) {
    EligibleSetNull obj1 = new EligibleSetNull();  
    System.out.println("Before Setting Null to Object.");
    obj1 = null;
    System.gc();
    System.out.println("After  Setting Null to Object.");
  }
}

Output

Before Setting Null to Object.
After  Setting Null to Object.
Unused Object is reclaim by Garbage Collector...

Explanation

Above example System.gc() function is called after setting the null value to object.So the object 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