I was trying to see usage of Runtime.freeMemory().
Documentation says it ‘Returns the amount of free memory in the Java Virtual Machine’
I executed a simple program test this. Program below:
public class Test {
public static void main(String a[]) throws Exception {
System.out.println("Total memory: " +Runtime.getRuntime().totalMemory());
System.out.println("Free memory: " +Runtime.getRuntime().freeMemory());
Integer intArr[]= new Integer[10000];
for(int i =0; i<10000;i++){
intArr[i] = new Integer(i+500);
}
System.out.println("Free memory: " +Runtime.getRuntime().freeMemory());
System.out.println("sample print :"+ intArr[0]);
System.out.println("sample print :"+ intArr[5000]);
System.out.println("sample print :"+ intArr[9999]);
}
}
Output:
Total memory: 67108864
Free memory: 61822408 < Before allocating 10000 objects>
Free memory: 61822408 < Size remains same even after allocating 10000 objects. why?>
sample print :500
sample print :5500
sample print :10499
Since the objects are created on heap, the ‘Free memory’ value printed second time should be less than the first output, right?
But it prints same value. Can anyone please explain why it print same value?
I know it is not the answer you wanted – but according to the JavaDoc –
freeMemoryreturns:Just to test it – I took your code and ran twice. Once with the array size set to 10,000 – and once with 100.
I also added another print just after:
When running with
10,000– I got the expected result, a decrease of40,0016 bytesin free memory just after the array instantiation.When running with
100I got the exact same amount of free memory before and after array instantiation – not the desired effect.As most answers already stated – as it is a native method – is JVM dependent and therefore can act differently on any platform.
I’m running on
Windows 7with theEclipse built-in JVM (v3.6).But I think the key word here is – approximation.