Java Runtime.freeMemory() returning bizarre results when adding more objects
- by Sotirios Delimanolis
For whatever reason, I wanted to see how many objects I could create and populate a LinkedList with. I used Runtime.getRuntime().freeMemory() to get the approximation of free memory in my JVM. I wrote this:
public static void main(String[] arg) {
Scanner kb = new Scanner(System.in);
List<Long> mem = new LinkedList<Long>();
while (true) {
System.out.println("Max memory: " + Runtime.getRuntime().maxMemory() + ". Available memory: " + Runtime.getRuntime().freeMemory() + " bytes. Press enter to use more.");
String s = kb.nextLine();
if (s.equals("m"))
for (int i = 0; i < 1000000; i++) {
mem.add(new Long((new Random()).nextLong()));
}
}
}
If I write in m, the app adds a million Long objects to the list. You would think the more objects (to which we have references, so can't be gc'ed), the less free memory. Running the code:
Max memory: 1897725952. Available memory: 127257696 bytes.
m
Max memory: 1897725952. Available memory: 108426520 bytes.
m
Max memory: 1897725952. Available memory: 139873296 bytes.
m
Max memory: 1897725952. Available memory: 210632232 bytes.
m
Max memory: 1897725952. Available memory: 137268792 bytes.
m
Max memory: 1897725952. Available memory: 239504784 bytes.
m
Max memory: 1897725952. Available memory: 169507792 bytes.
m
Max memory: 1897725952. Available memory: 259686128 bytes.
m
Max memory: 1897725952. Available memory: 189293488 bytes.
m
Max memory: 1897725952. Available memory: 387686544 bytes.
The available memory fluctuates. How does this happen? Is the GC cleaning up other things (what other things are there on the heap to really clean up?), is the freeMemory() method returning an approximation that's way off? Am I missing something or am I crazy?