Example using Garbage Collector

Here we explore how JVM call to Garbage collector -gc internally.
For this we write two class one is Employee and another is TestGarbageCollection.


Class Employee.java




package com.javaforcast;
public class Employee {
 int empid;
 String empname;
 public Employee(int empid,String empname){
  this.empid=empid;
  this.empname=empname;
 }
 public void finalize(){
  System.out.println("in finalize(): Resousce release");
 }
}


TestGarbageCollection.java


 * @Author: Arbind
  * @Garbage collection example
  */
package com.javaforcast;
public class TestGarbageCollection {
  public static void main(String[] args) {
  Employee e1=new Employee(100,"Abind");
  Employee e2=new Employee(101,"Kumar");
  Employee e3=new Employee(102,"Sharma");
  Employee e4=new Employee(103,"Arbind");
  Employee e5=new Employee(1004,"Arbind");
  System.runFinalization();
  System.gc();
  e2=e1;
  System.runFinalization();
  System.gc();
  e3=null;
      
System.runFinalization();
  System.gc();
 }
}