How to invoke Java Garbage Collection Programmatically?

by Jyotheeswara Naidu Malapati

Java actually provides a facility in invoking garbage collection explicitly, there is no guarantee that it will be run. You could write a program and request GC to run but you can’t actually force it to run.

How to request GC to run?

System.gc() method can be used to request garbage collection. and System.runFinalization() method to tell do any pending finalizers to be run for all the eligible objects for GC.

Method syntax:

static void gc() // Requests GC to be run
static void runFinalization() // Requests any pending finalizers to be run on eligible objects of GC

How to determine if there is any free space available in JVM for new objects?

Java application has a unique ‘Runtime’ object which can be used to intract with JVM. Use Runtime.getRuntime() to get hold of runtime object. The runtime object provides various methods related to memory.

For more such methods. Please refer to api documentation

long freeMemory() : method returns an amount of free memory in bytes available for new objects Use long totalMemory() : to find total amount of memory in bytes available in JVM.

Now, Let’s take a look into the sample program which uses the gc,runtime method calls

Sample Program

/**
 * @author codedairy.com
 *
 */
public class MyGCProgram {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		int nums = 2;//Integer.parseInt(args[0]); // no. of Objects to be created

		Runtime runtimeEnv = Runtime.getRuntime();

		System.out.println("Total memory in JVM : " + runtimeEnv.totalMemory());
		System.out.println("Free memory : " + runtimeEnv.freeMemory());

		for ( int i = 0 ; i < nums ; i ++ )
		{
			new Base();
		}

		System.out.println("Free memory after Objects creation: " + runtimeEnv.freeMemory());

		//Call GC
		System.gc();

        System.out.println("Free memory after GC is run: "+ runtimeEnv.freeMemory() );

	}

}

/**
 *
 * @author codedairy.com
 *
 */
public class Base {

	HashMap table = new HashMap();
	public Base() {

		for ( int i = 0 ; i < 1000 ; i++ )
		{
			table.put("x"+i, new String("value+1"));

		}
	}
	@Override
	protected void finalize() throws Throwable {

		System.out.println(this.getClass().getName()+ ":I'm dying ");
		super.finalize();
	}
}

Output:

Total memory in JVM : 16252928
Free memory : 15963816
Free memory after Objects creation: 15601896
Free memory after GC is run: 15893160
Base:I'm dying
Base:I'm dying

Please remember the below

  • Finalizers: There isn’t any guarantee that the eligible objects for GC will have their finalizers be executed. Also, the programmers shouldn’t make any assumptions on the order of finalizers methods gets executed of an objects and the order of the objects gets garbage collected.
  • Whenever the program terminates, the allocated memory for the program execution will be reclaimed by operating system.
  • GC will never care about whether your program has enough memory to run or not.You program can rely on GC to be run when there is a low memory You would get an OutofMemoryExceptions when there isn’t enough memory available

Thanks for reading my post. please do not hesitate to post your comments or ask any questions below ( or even you find any mistakes too :-) )

Leave a Comment