This section a tutorial example on how to find out when the garbage collector automatically performing the garbage collection process.
To understand when the JVM will ask the garbage collector to perform the garbage collection process,
I wrote the following tutorial example to run a loop of many steps. In each step, a new 1-MB object is
created and an old 1-MB object is freed up, except for the first 32 steps:
/**
* GarbageCollection.java
* Copyright (c) 2003 by Dr. Herong Yang
*/
class GarbageCollection {
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()));
try {
Thread.sleep(1000/10);
} catch (InterruptedException e) {
System.out.println("Interreupted...");
}
}
}
private static Object getOneMega() {
return new long[1024*128]; // 1MB
}
}
Note that:
The method getOneMega() is used to create a 1-MB object, which is an array of "long"
with 1024*128 = 131072 elements. Since size of data type "long" is 8 bytes, the total size
of the array is 131072 * 8 = 1048576 bytes (1MB).
Between step 0 and 31, no garbage collection happened, because there was no unused objects.
JVM increased the total memory 5 times to 45334528 bytes, to have enough space for 32 new objects.
From step 32 to 41, unused object are available for garbage collection.
But JVM decided to use its free memory for new objects.
At step 42, the free memory was very low, 1184608 bytes.
JVM decided to increase the total memory, and call for garbage collection.
After step 43, JVM stopped to increase total memory. It called for garbage collection
when its free memory is too low.