You are here

Java program to perform garbage collection

Java program to perform garbage collection: Free memory in Java virtual machine is printed and then garbage collection is done using gc method of RunTime class, freeMemory method returns the amount of free memory in JVM, getRunTime method is used to get reference of current RunTime object.

Java programming source code

  1. import java.util.*;
  2.  
  3. class GarbageCollection
  4. {
  5.   public static void main(String s[]) throws Exception
  6.   {
  7.     Runtime rs = Runtime.getRuntime();
  8.     System.out.println("Free memory in JVM before Garbage Collection = "+rs.freeMemory());
  9.     rs.gc();
  10.     System.out.println("Free memory in JVM after Garbage Collection = "+rs.freeMemory());
  11.   }
  12. }

Download Garbage collection program class file.

Output of program:
Java program for garbage collection output

Obviously, the amount of available memory after garbage collection will be different on your computer. Numbers are not important, what is important is that the memory available is more after garbage collection. You can use the code in a program or a project which uses large amount of memory or where new objects are created frequently but are required for a short span of time.