Eligible Object for Garbage Collection when the references of that object or instance lifetime will expire

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

Instance lifetime or Scope of Object

Object References is vanishes at the end of the scope.No way to access the object, because the only reference to it is out of scope. But still memory which is created by the object will Dangling in heap memory.So after out of scope instance is eligible for garbage collection.

Below Example - Garbage Collector will call when object references goes out of scope

public class EligibleScope {  
  protected void finalize(){
   System.out.println("Unused Object is reclaim by Garbage Collector:"+this);
  }
  public void createObject(){
   EligibleScope obj1 = new EligibleScope();
   System.out.println("obj1 address :"+obj1);
  }
  public static void main(String[] args) {
   EligibleScope obj = new EligibleScope();
   System.out.println("Before called Garbage Collector");
   System.out.println("obj  address :"+obj);
   obj.createObject();   
   System.gc();
   System.out.println("After  called Garbage Collector");
  }
}

Output

Before called Garbage Collector
obj  address :EligibleScope@dc8569
obj1 address :EligibleScope@1bab50a
After  called Garbage Collector
Unused Object is reclaim by Garbage Collector:EligibleScope@1bab50a

Explanation

Above example System.gc() function is called after the createObject method.obj1 object is created inside that function and its lifetime also over once that function gets over. So that obj1 is reclaimed and it is called the finalize method.

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

2 comments:

  1. It is nice post and I found some interesting information on this blog, keep it up. Thanks for sharing. . .
    Hire Dedicated Angularjs Developer in India

    ReplyDelete
  2. Thanks for sharing such an useful and informative post.
    Java course in Pune

    ReplyDelete