Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Runtime.freeMemory() show more memory after constructing an object?

I am trying to figure the size of a hashmap in memory without a profiler. So I did the following:

HashMap<Integer, String> map = new HashMap<Integer, String>();
long start = System.currentTimeMillis();
lotsOfGC();
long freeMemoryBeforeConstruction = Runtime.getRuntime().freeMemory();
System.out.println("memory before = " + freeMemoryBeforeConstruction);
for(int i = 0; i < numbers.length; i++) {
    String value = "value"+ i;
    map.put(i, value);
}
long end = System.currentTimeMillis();
lotsOfGC();
long freeMemoryAfterConstruction = Runtime.getRuntime().freeMemory();
System.out.println("memory after= " + freeMemoryAfterConstruction );

Where lotsOfGC is just:

static void lotsOfGC() {
        for (int i = 0; i < 20; i++) {
            System.gc();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

The result I get is:

memory before =    76083464
memory after    =  722062528

Can someone please explain to me why the free memory after creating the hashmap is bigger?

Update: After reading the comment of @Patricia Shanahan I used the total memory and got:

memory before        =  76083464  
total memory before  =  96468992  
memory after         = 735235264  
total memory after   = 755367936
like image 336
Jim Avatar asked Jun 28 '15 19:06

Jim


1 Answers

The currently allocated memory is the difference

Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()

Allocating an object, especially a large one, may require the JVM to obtain additional memory from the operating system. That is a relatively expensive operation, so it is more efficient for the JVM to request memory in large chunks. When it obtains more memory than the current allocation requires, both total memory and free memory will increase.

like image 62
Patricia Shanahan Avatar answered Nov 09 '22 17:11

Patricia Shanahan