[英]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: lotsOfGC
只是:
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
记忆之前= 76083464
memory after = 722062528内存= 722062528之后
Can someone please explain to me why the free memory after creating the hashmap is bigger? 有人可以向我解释为什么创建hashmap 后的可用内存更大?
Update: After reading the comment of @Patricia Shanahan I used the total memory and got: 更新:在阅读@Patricia Shanahan的评论后,我使用了总记忆并获得:
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. 分配对象(尤其是大对象)可能需要JVM从操作系统获取额外的内存。 That is a relatively expensive operation, so it is more efficient for the JVM to request memory in large chunks.
这是一个相对昂贵的操作,因此JVM以大块的形式请求内存效率更高。 When it obtains more memory than the current allocation requires, both total memory and free memory will increase.
当它获得的内存超过当前分配所需的内存时,总内存和可用内存都将增加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.