I was planning to use getRuntime().freeMemory()
to get a rough estimate of how much memory is consumed by a java method . I was trying to achieve it with the following:
long beforeUsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
foo();
long afterUsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
long actualMemUsed=afterUsedMem-beforeUsedMem;
For testing if this could actually work, I ran the code below
long beforeUsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
List<Integer> list = new ArrayList<>();
for(int i = 0 ;i<1000;i++)
list.add(i);
long afterUsedMem=Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
long actualMemUsed=afterUsedMem-beforeUsedMem;
System.out.println("mem used "+actualMemUsed);
However, the output of the program comes out to be
mem used 0
However, if I loop from 0 -> 100000 , the output comes out to be
mem used 2684368
Can anyone explain why jvm may be working like this?