This section provides a tutorial example on how to use the garbage collection method gc() on the default Runtime object to control the garbage collection process by yourself.
If you do not like the way JVM automatically performing the garbage collection process.
you can use the gc() method of the default Runtime object to control the garbage collection process by yourself.
To test this fc() method, I modified the tutorial example presented in the previous section
to explicitly perform garbage collection whenever the free memory size is below 10 MB:
/**
* GarbageCollectionForced.java
* Copyright (c) 2003 by Dr. Herong Yang
*/
class GarbageCollectionForced {
public static void main(String[] a) {
int steps = 10000;
int size = 32;
Object[] queue = new Object[size];
Runtime rt = Runtime.getRuntime();
System.out.println("Memory: Maximum Total Free Used");
for (int m=0; m<steps; m++) {
for (int n=0; n<size-1; n++)
queue[size-n-1] = queue[size-n-2];
queue[0] = getOneMega();
System.out.println(m+" "+rt.maxMemory()
+" "+rt.totalMemory()+" "+rt.freeMemory()
+" "+(rt.totalMemory()-rt.freeMemory()));
// Forcing a garbage collection
if (rt.freeMemory()<10485760) {
rt.gc();
System.out.println(m+" "+rt.maxMemory()
+" "+rt.totalMemory()+" "+rt.freeMemory()
+" "+(rt.totalMemory()-rt.freeMemory())
+" //Garbage collected");
}
try {
Thread.sleep(1000/10);
} catch (InterruptedException e) {
System.out.println("Interreupted...");
}
}
}
private static Object getOneMega() {
return new long[1024*128]; // 1MB
}
}
Running this modified sample program with JDK 1.6, I got the following output:
Between step 0 and 13, the gc() method is called on every step because the free memory was very low.
But gc() did not free up any object, because
there was no unused objects in the memory.
The gc() method actually caused the JVM to obtain more total memory when the free memory was low.
See steps 2, 3, ..., 13. In another word, the gc() method does not only frees up unused objects,
it also tries to obtain more total memory if needed.