JVM为什么要采用分代算法

一个运行的系统,系统里面的每一个对象,他们的生命周期是不一样的,大部分是短命,小部分是长命。
所以不同的年龄对象,分开处理,即分代处理,年轻的对象放在年轻代,年老的对象放在老年代。

image.png
image.png
image.png
image.png
image.png
image.png
总结:
由于对象的生命周期不同,才采用了分代存储,短命存年轻代,长命存老年代。

案例实战:什么对象绕过年轻代,直接进入老年代?

  1. public class GcTest01 {
  2. private static final int _1MB = 1024* 1024;
  3. /**
  4. -Xms30M
  5. -Xmx30M
  6. -XX:+PrintGCDetails
  7. -XX:+PrintHeapAtGC
  8. */
  9. public static void main(String[] args) throws InterruptedException {
  10. byte[] allocation1 = new byte[2*_1MB];
  11. System.out.println("--------创建2M后--------");
  12. byte[] allocation2 = new byte[2*_1MB];
  13. System.out.println("--------创建2M后--------");
  14. byte[] allocation3 = new byte[4*_1MB];
  15. System.out.println("--------创建4M后--------");
  16. }
  17. }

image.png

  1. --------创建2M后--------
  2. --------创建2M后--------
  3. --------创建4M后--------
  4. Heap
  5. PSYoungGen total 9216K, used 7407K [0x00000000ff600000, 0x0000000100000000, 0x0000000100000000)
  6. eden space 8192K, 90% used [0x00000000ff600000,0x00000000ffd3bc00,0x00000000ffe00000)
  7. from space 1024K, 0% used [0x00000000fff00000,0x00000000fff00000,0x0000000100000000)
  8. to space 1024K, 0% used [0x00000000ffe00000,0x00000000ffe00000,0x00000000fff00000)
  9. ParOldGen total 20480K, used 4096K [0x00000000fe200000, 0x00000000ff600000, 0x00000000ff600000)
  10. object space 20480K, 20% used [0x00000000fe200000,0x00000000fe600010,0x00000000ff600000)
  11. Metaspace used 3303K, capacity 4496K, committed 4864K, reserved 1056768K
  12. class space used 357K, capacity 388K, committed 512K, reserved 1048576K