I was using Runtime.getRuntime().totalMemory() and freeMemory() to calculate memory. However, I am confused by the results.
I already read the posts in:
What are Runtime.getRuntime().totalMemory() and freeMemory()?
a question on Runtime.getRuntime().totalMemory()
Here is my demo code:
package test;
class Memory
{
public static long used()
{
long total=Runtime.getRuntime().totalMemory();
long free=Runtime.getRuntime().freeMemory();
return (total-free);
}
}
package test;
import java.util.ArrayList;
public class MemTestQuestion {
    private static final long _10M = 10000000;
    public static void main(String[] args) {
        int runCount=10;
        for (int i = 0; i < runCount; i++) {
            arrayListMemTest();
        }
    }
    public static void arrayListMemTest()
    {
        long startTime = System.currentTimeMillis();
        long startMem=Memory.used();
        ArrayList<Integer>al= new ArrayList<Integer>();
        for (int i = 0; i < _10M; i++) {
            al.add(1000);
        }
        long endMem= Memory.used();
        long endEndTime = System.currentTimeMillis();
        long timeLast = endEndTime - startTime;
        long memUsed = endMem-startMem;
        System.out.print("lasts:"
                + timeLast + "ms = "+timeLast/1000.0+"s\t");
        System.out.println("mem used:"
                +memUsed+"bytes = "+new java.text.DecimalFormat("#.00").format(memUsed/(1024*1024.0))+"M");
        System.gc();
    }
}
Here are results when runCount=1(a variable located in Main method):
lasts:3606ms = 3.606s   mem used:214644488bytes = 204.70M
Here are results when runCount=10:
lasts:3643ms = 3.643s   mem used:214644488bytes = 204.70M
lasts:389ms = 0.389s    mem used:254054928bytes = 242.29M
lasts:366ms = 0.366s    mem used:219163424bytes = 209.01M
lasts:242ms = 0.242s    mem used:256265992bytes = 244.39M
lasts:222ms = 0.222s    mem used:255523768bytes = 243.69M
lasts:225ms = 0.225s    mem used:253843192bytes = 242.08M
lasts:253ms = 0.253s    mem used:253967736bytes = 242.20M
lasts:236ms = 0.236s    mem used:253994680bytes = 242.23M
lasts:234ms = 0.234s    mem used:254066232bytes = 242.30M
lasts:233ms = 0.233s    mem used:254091448bytes = 242.32M
What confused me most was that when the runCount=10,  the most results are around 240M. But when the runCount=1, the results are around 200M.
I guess this is because the JAVA JVM does not collect garbage in time, so the first result are more convicing. Am I right? If not, can someone provide some clues or other suggestions? Thanks in advance.
The purpose of the demo code was trying to compare the standard java containers and ones from third party.
 
     
     
    