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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With