C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
And: Using a lower-level language, like C or Rust can help with allocation programs.