Saturday, April 4, 2015

Java program to perform garbage collection

Java program to perform garbage collection

This program performs 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 amount of free memory in jvm, getRunTime method is used to get reference of current RunTime object.

Java programming source code

import java.util.*;
 
class GarbageCollection
{
   public static void main(String s[]) throws Exception
   {
      Runtime rs =  Runtime.getRuntime();
      System.out.println("Free memory in JVM before Garbage Collection = "+rs.freeMemory());
      rs.gc();
      System.out.println("Free memory in JVM after Garbage Collection = "+rs.freeMemory());
   }
}
Download Garbage collection program class file.
Output of program:
garbage collection
Obviously the amount of available after garbage collection will be different on your computer. Numbers are not important, what is important is that amount of memory available is more than before. You can use this code in your program or projects which uses large amount of memory or where frequently new objects are created but are required for a short span of time.

No comments:

Post a Comment

TestNG - Can i use the 2 different data providers to same @test methods in TestNG?

public Object [][] dp1 () { return new Object [][] { new Object [] { "a" , "b" }, new Obje...