Memory management is the process of recognizing when allocated objects are no longer needed, deallocating (freeing) the memory used by such objects, and making it available for subsequent allocations.

In Java, memory management is the responsibility of program called the garbage collector (commonly called as GC). The garbage collector in Java, automatically runs at regular intervals to perform memory management activities. Let’s see how to call garbage collector in Java program. The objective of this demo is to get familiar with the process of garbage collection.

Note
Please note that a program should not call the garbage collector explicitly. Even if the garbage collector is called in a program, it is not certain that it will run at that very moment. Calling the garbage collector is a request (not a command) to the JVM to invoke the process. It is the JVM which decides when to run the garbage collector. Running the garbage collector explicitly when a program is in execution is a resource intensive job.

A Java project is created in Eclipse with the following structure

Project structure in Eclipse

The code for the GCDemo.java and Student.java classes are as follows

GCDemo.java
package com.planetofbits.gc.demo;

import java.io.IOException;
import java.util.ArrayList;

public class GCDemo
{
	public static void main(String[] args) throws IOException
	{
		java.io.PrintStream out = System.out;

		// Get the Runtime instance of the JVM
		Runtime rt = Runtime.getRuntime();

		out.println("--- Initial state of memory ---");

		// Returns the maximum amount of memory that the Java virtual
		// machine will attempt to use.
		out.println("Maximum memory (in bytes): " + rt.maxMemory());
		// Returns the total amount of memory in the Java virtual machine.
		out.println("Total memory (in bytes): " + rt.totalMemory());
		// Returns the amount of free memory in the Java Virtual
		out.println("Free memory (in bytes): " + rt.freeMemory());

		ArrayList studentList = new ArrayList();
		for (int i = 1; i <= 1000; i++)
		{
			Student student = new Student();
			student.setRollNo(i);
			student.setName("S" + i);
			studentList.add(student);
		}

		out.println("\n--- After creating the ArrayList ---");

		long freeMemoryBeforeGC = rt.freeMemory();
		out.println("Free memory (in bytes): " + freeMemoryBeforeGC);

		// Removes all of the elements from this list.
		// The list will be empty after this call returns.
		studentList.clear();
		// Null reference the ArrayList handle
		studentList = null;

		// Runs the finalization methods of any objects pending finalization.
		rt.runFinalization();
		out.println("\n--- Garbage Collector invoked ---");
		// Call the garbage collector
		rt.gc();

		out.println("\n--- After garbage collection ---");
		long freeMemoryAfterGC = rt.freeMemory();
		out.println("Free memory (in bytes): " + freeMemoryAfterGC);
		out.println("Memory freed by GC (in bytes): " + (freeMemoryAfterGC - freeMemoryBeforeGC));
	}

}
Tip
System.gc(); is another way to invoke the garbage collector. However, if we look inside the java.lang.System.gc() method, it internally calls the Runtime.getRuntime().gc()
It is more of a convenience to call System.gc() with no technical difference. In this case, gc() is a class method of java.lang.System whereas in java.lang.Runtime, it is an instance method.
Student.java
package com.planetofbits.gc.demo;

public class Student
{
	private int rollNo;
	private String name;

	public int getRollNo()
	{
		return rollNo;
	}

	public void setRollNo(int rollNo)
	{
		this.rollNo = rollNo;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}
}

To view what the Garbage Collector is doing when it is invoked, pass -verbose:gc to JVM as shown below

Step 1

Open Eclipse and in the toolbar menu, go to Run -> Run Configurations...

Go to Run Configuration

Step 2

In the left pane of Run Configurations window, navigate to the Java Application node and select the Java application for which you need to increase the heap size. Then in the right pane, click on the Arguments tab.

Provide-VM-params-for-verbose-GC

In the VM Arguments section, type the following argument:
-verbose:gc

Click on Apply button to save the changes.

Provide-VM-params-for-verbose-GC

Running the GCDemo.java class gives the following output on my machine.

Note
Please not that the output of this program depends on the platform environment in which this program is executed. If you execute this code on your machine, it will not match with the output shown below.
Output of GCDemo

In the above output, the free memory after garbage collection is higher than the initial memory. This indicates that some memory has been reclaimed by the garbage collection program. However, as already said, please be aware that there might be a completely different output on your machine.

How to call Garbage Collector in Java

Comments, Questions or Suggestions: