HomeSearch

Java System.gc, Runtime.getRuntime and freeMemory

This Java example page uses the System.gc method and the Runtime.getRuntime method. It calls freeMemory to measure memory usage.
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.
An example 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.

GetRuntime: We call Runtime.getRuntime to get a Runtime object. We can store a Runtime in a local variable, but this is not always needed.

FreeMemory: This method returns the number of unused bytes in the Java runtime. We can measure how much memory is used with freeMemory.

Java program that uses System.gc, 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)); } } Output BEFORE:125535480 DURING:121535464 AFTER:122580096 CHANGE AFTER GC: -1044632
Notes, 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.Int Arrays
Notes, avoiding GC. 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.

And: Using a lower-level language, like C or Rust can help with allocation programs.

A final note. The freeMemory() method is useful in real programs and benchmarks. It can help inform us how much memory we are using (and wasting).
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls