HotSpot JVM上的内存管理:
Another desirable garbage collector
characteristic is the limitation of
fragmentation. When the memory for
garbage objects is freed, the free
space may appear in small chunks in
various areas such that there might
not be enough space in any one
contiguous area to be used for
allocation of a large object. One
approach to eliminating fragmentation
is called compaction, discussed among
the various garbage collector design
choices below.
此行为可能非常依赖于垃圾回收的特定实现.例如:
Parallel Mark Compact
Stop-the-world
Heap divided into fixed-size chunks (> 2kb now, will likely increase or be
subject to ergonomics)
Chunk is unit of live data summarization
Parallel mark
Record live data addresses in external bitmap
Find per chunk live data size
Find dense chunks, i.e., ones that are (almost) full of live objects
我做了这个样本(使用滥用字符串连接来消耗更多内存):
public class TestFreeMemory {
static void allocateSomeMemory(){
long[][] array = new long[400][400];
}
public static void main(String ... args){
Runtime rt = Runtime.getRuntime();
allocateSomeMemory(); // once we leave, our array is not reachable anymore
System.out.println("Free Memory (Before GC): " + rt.freeMemory());
rt.gc();
System.out.println("Free Memory (After GC): " + rt.freeMemory());
String a = new String("A");
for(int i = 0; i < 100; i++){
a+="B";
}
System.out.println("Free Memory (After String Creation): " + rt.freeMemory());
// Less free memory expected.
}
}
输出:
Free Memory (Before GC): 3751800
Free Memory (After GC): 5036104
Free Memory (After String Creation):
5012048
如果我在循环中使用相对较少的迭代次数(例如10),额外的空间不会出现在freeMemory()中,我会得到这样的结果:
Free Memory (Before GC): 3751800
Free Memory (After GC): 5036040
Free Memory (After String Creation): 5036040