Garbage collection in Java

Created with Sketch.

 

Garbage collection in Java

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

Garbage collection program in Java

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());
}
}

 

Output of program:
Java program for garbage collection output

The amount of available memory after garbage collection will be different on your computer. Numbers are not significant; what is essential is that the memory available is more after garbage collection. You can use the code in a program or an application that uses a large amount of memory or where new objects are created frequently but required for a short time.

Leave a Reply

Your email address will not be published. Required fields are marked *