jvm垃圾收集的问题

VM参数:-verbose:gc -Xms20M -Xmx20M -Xmn10M -XX:+PrintGCDetails -XX:SurvivorRatio=8 -XX:-HandlePromotionFailure

这里是主要代码:
allocation1 = new byte[2 * _1MB]; //分配2MB,下面一样
allocation2 = new byte[2 * _1MB];

allocation3 = new byte[2 * _1MB];

allocation1 = null;

allocation4 = new byte[2 * _1MB]; //到这里就有YGC了,新生代不是有9MB可以用么?

[GC [DefNew: 6471K->135K(9216K), 0.0042747 secs] 6471K->4231K(19456K), 0.0043168 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]

刚开始就已经用了2MB了
[code="java"]
public static final int _1MB = 1024 * 1024;

@SuppressWarnings("unused")
public static void main(String ars[]) throws InterruptedException {
    showMemory();
    byte[] a = new byte[2 * _1MB];
    showMemory();
    byte[] b = new byte[2 * _1MB];
    showMemory();
    byte[] c = new byte[2 * _1MB];
    showMemory();
    byte[] d = new byte[2 * _1MB];
    showMemory();
    a = null;
    showMemory();
    byte[] e = new byte[2 * _1MB];
    showMemory();
}

private static void showMemory() throws InterruptedException {
    long total;
    long free;
    total = Runtime.getRuntime().totalMemory();
    free = Runtime.getRuntime().freeMemory();
    System.out.println("total:" + total + "\tfree:" + free + "\tused:"
            + (total - free));
    Thread.sleep(1000);
}

[/code]

young:from:to:old
内存是这样的(from,to)都是Survivor
XX:SurvivorRatio=8
young:from=8:1
from:to=1:1

所有young=(8/10)*10M=8M

我刚测试了下,确实是gc了
原因是在jvm容器加载的时候其他的东西还需要内存

[GC [PSYoungGen: 6472K->152K(9216K)] 6472K->4248K(19456K), 0.0056470 secs] [Times: user=0.00 sys=0.01, real=0.01 secs]

这个可以看出来,垃圾回收以后,还剩下了152k的空间被占据。
所以,你这个实验中,没有流出这个空间来。
再分配2M的时候正好不够了。

另外,这里的Minor GC发生的时候,还没有退出当前作用域,所以Minor GC后的2M和新请求的2M进入了老年代。4M / 10M = 40%
PSOldGen total 10240K, used 4096K [0xb2450000, 0xb2e50000, 0xb2e50000)
object space 10240K, 40% used [0xb2450000,0xb2850020,0xb2e50000)

最后,不要用ide。因为ide加入了一些别的参数(可能)。例如我这里的ide的结构就和上面不同:不是152了!
[GC [PSYoungGen: 8192K->442K(9216K)]