1

I made a test program to test the Runtime.freeMemory() method.

public class RuntimeFreeMemory {

    public static void main(String[] args) {
        Runtime r = Runtime.getRuntime();
        System.out.println(r.freeMemory()); // 246939608

        String[] arr = new String[10000000];
        for (int i = 0; i < 10000000; i++)
            arr[i] = new String();

        System.out.println(r.freeMemory()); // 517655928
    }
}

Of course, these are big numbers, but I really wanted to test it as numbers like 10000 wouldn't cut it. But when I ran it, I got some unexpected numbers. I thought the end free memory would go down or stay somewhat the same as the initial free memory, but instead they went over double what the initial free memory was. I ran this multiple times and it was always something around these values. Can somebody explain this?

TheXDShrimp
  • 116
  • 13

1 Answers1

1

The freeMemory reported may be affected by GC and by the fact that the heap has been expanded because of your array allocations. It might be interesting to also print r.totalMemory at the beginning and at the end and compare.

When the JVM starts, it doesn't actually allocate (by default) whole heap memory upfront - it's just "reserved" and later "committed" if/when needed (at that point, heap is expanded).

You can try to set -Xms and -Xmx explicitly to the same value and will likely get more expected results.

E.g. by using -Xms8g -Xmx8g I got following:

    public static void main(String[] args) {
        Runtime r = Runtime.getRuntime();
        System.out.println(r.freeMemory()); // 8581851136
        System.out.println(r.totalMemory()); // 8589934592 

        System.out.println("Process PID: " + ProcessHandle.current().pid());

        String[] arr = new String[100000000];
        for (int i = 0; i < 100000000; i++)
            arr[i] = new String();

        System.out.println(r.freeMemory()); // 5717141504
        System.out.println(r.totalMemory()); // 8589934592
    }

    // compare results when using ONLY -Xmx8g
    // 537178112
    // 541065216
    // 3240407040
    // 6104809472

Note: Using -Xms still doesn't (usually) mean that the memory is resident in RAM: Java heap Xms and linux free memory different

Juraj Martinka
  • 3,991
  • 2
  • 23
  • 25