This section provides a tutorial example on how to run the Garbage Collector explicitly by calling the gc() method on the Runtime instance.
In the next test, I want to learn how to use
runFinalization() and gc() methods to force the Garbage Collector to run:
/**
* RuntimeGarbageCollection.java
* Copyright (c) 2010 by Dr. Herong Yang, herongyang.com
*/
class RuntimeGarbageCollection {
public static void main(String[] a) {
java.io.PrintStream out = System.out;
Runtime rt = Runtime.getRuntime();
out.println("Starting the test...");
out.println(" Total memory: " + rt.totalMemory());
out.println(" Free memory: " + rt.freeMemory());
out.println("Freeing unused objects...");
rt.runFinalization();
rt.gc();
out.println(" Total memory: " + rt.totalMemory());
out.println(" Free memory: " + rt.freeMemory());
out.println("Allocating and discarding object...");
bigObect();
out.println(" Total memory: " + rt.totalMemory());
out.println(" Free memory: " + rt.freeMemory());
out.println("Freeing unused objects...");
rt.runFinalization();
rt.gc();
out.println(" Total memory: " + rt.totalMemory());
out.println(" Free memory: " + rt.freeMemory());
}
public static void bigObect() {
Object o = new long[2*1024*128]; // 2 MB
o = null;
}
}
When executed on my Windows XP system with JDK 1.6.0,
I got this result:
C:\herong\jvm>java RuntimeGarbageCollection
Starting the test...
Total memory: 5177344
Free memory: 4993128
Freeing unused objects...
Total memory: 5177344
Free memory: 5049032
Allocating and discarding object...
Total memory: 5177344
Free memory: 2951864
Freeing unused objects...
Total memory: 5177344
Free memory: 5049032
The test result tells me that:
Right after the JVM started, my application and JVM used 5177344 - 4993128 = 184216 bytes of memory.
After running the garbage collector, memory usage went down to
5177344 - 5049032 = 128312 bytes, freeing up 55904 bytes of memory occupied by discarded objects
left from the JVM startup step.
After allocating and discard a 2 MB array object, memory usage went up to
5177344 - 2951864 = 2225480. The discard object was still occupying its memory.
After running the garbage collector gain, memory usage went down to
5177344 - 5049032 = 128312 bytes again, freeing up 2097168 bytes of memory occupied by the discarded
2 MB array object.
Conclusion: running the garbage collector explicitly does free up memory used by discarded objects.
But you don't have to do this in your application, since JVM has a separate thread running the garbage collector automatically.