Java Garbage Collector Program

Garbage collection  in Java

Garbage collection is also known as GC is nothing but to reclaiming the unused memory. In java memory management done automatically. GC is a process of recollecting and identifying the unused portion of heap memory and then delete it. An unused object or unreferenced object will occupy memory space which has no use, so it has to be deleted by the automatic garbage collection in Java. Sometimes it may required to do some clean up work manually. For this we can override the finalize method. This method will do the clean up job. We can also use gc() method. This way it will manage memory efficiently.


Clean up process using gc() method
import java.util.*;

class GarbageCollection
{
   public static void main(String s[]) throws Exception
   {
      Runtime free =  Runtime.getRuntime();
      System.out.println("Free memory in JVM before Garbage Collection = " + free.freeMemory());
      // Calling the gc() method
      free.gc();
      System.out.println("Free memory in JVM after Garbage Collection = " + free.freeMemory());
   }
}


Finalize method
finalize() is used when performing some job or task before it destroy such as when we need to close or release a resource.
protected void finalize() throws Throwable
{
        try
        {
            System.out.println("clean up process");
         }
       catch(Throwable temp)
        {
            throw temp;
        }
       finally
      {
            System.out.println("calling Super Class of Finalize class");
            super.finalize();
        }
     

    }


SHARE THIS
Previous Post
Next Post