System.gc
Java runs in a virtual
machine. Memory is allocated, and freed, without any programmer intervention. This makes programs easier to develop.
Rarely, a programmer may want to force a garbage collection. This is usually a bad idea. But it can sometimes help, even in just debugging a program.
This program mainly is used to test the Runtime.getRuntime
, freeMemory
, and gc()
methods. So it is not a useful program in other ways.
Runtime.getRuntime
to get a Runtime object. We can store a Runtime in a local variable, but this is not always needed.freeMemory()
method returns the number of unused bytes in the Java runtime. We can measure how much memory is used with freeMemory
.public class Program { public static void main(String[] args) { long total = Runtime.getRuntime().freeMemory(); // Allocate an array and ensure it is used by the program. int[] array = new int[1000000]; array[0] = 1; if (array[0] == 3) { return; } long total2 = Runtime.getRuntime().freeMemory(); // Collect the garbage. System.gc(); long total3 = Runtime.getRuntime().freeMemory(); // Display our memory sizes. System.out.println("BEFORE:" + total); System.out.println("DURING:" + total2); System.out.println("AFTER:" + total3); System.out.println("CHANGE AFTER GC: " + (total2 - total3)); } }BEFORE:125535480 DURING:121535464 AFTER:122580096 CHANGE AFTER GC: -1044632
System.gc
The gc()
method is invoked in the above program. It causes the free memory to increase by about 1 MB. This is because the int
array is freed.
Basically, calling System.gc
is a bad idea. To optimize a program to run more efficiently, you can try to avoid object allocations in the first place.
The freeMemory()
method is useful in real programs and benchmarks. It can help inform us how much memory we are using (and wasting).