Java Reference
In-Depth Information
The
System
class contains a convenience method called
gc()
, which is equivalent to executing the
Runtime.getRuntime().gc()
statement. You can also use the following statement to run the garbage collector:
// Invoke the garbage collector
System.gc();
The program in Listing 11-1 demonstrates the use of the
System.gc()
method. The program creates 2,000 objects
of the
Object
class in the
createObjects()
method. The references of the new objects are not stored. You cannot
refer to these objects again, and hence, they are garbage. When you invoke the
System.gc()
method, you suggest to
the JVM that it should try to reclaim the memory used by these objects. The memory freed by the garbage collector is
displayed in the output section. Note that you will more than likely get a different output when you run this program.
Listing 11-1.
Invoking Garbage Collection
// InvokeGC.java
package com.jdojo.gc;
public class InvokeGC {
public static void main(String[] args) {
long m1, m2, m3;
// Get a runtime instance
Runtime rt = Runtime.getRuntime();
for(int i = 0; i < 3; i++){
// Get free memory
m1 = rt.freeMemory();
// Create some objects
createObjects(2000);
// Get free memory
m2 = rt.freeMemory();
// Invoke garbage collection
System.gc();
// Get free memory
m3 = rt.freeMemory();
System.out.println("m1=" + m1 + ", m2=" + m2 + ", m3=" +
m3 + "\nMemory freed by gc()=" + (m3 - m2));
System.out.println("-------------------------");
}
}