Home
Java
System.gc, Runtime.getRuntime and freeMemory
This page was last reviewed on Sep 11, 2023.
Dot Net Perls
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.
Start We call Runtime.getRuntime to get a Runtime object. We can store a Runtime in a local variable, but this is not always needed.
Next The 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
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.
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).
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 11, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.