zoukankan      html  css  js  c++  java
  • CMS垃圾收集器小实验之CMSInitiatingOccupancyFraction参数

    背景

    测试CMSInitiatingOccupancyFraction参数,测试结果和我的预期不符,所以花了一点时间一探究竟,文中有一些细节问题搞得不是特别清楚,但是也解决了我的困惑,在此记录一下。

    参数说明

    触发cms gc的老年代占用率,比如设置-XX:CMSInitiatingOccupancyFraction=80,那么在老年代占用率达到80%时触发cms gc。

    CMSWaitDuration说明

    cms gc线程定时执行的时间间隔,默认为2s一次。

    测试环境准备

    1.下载fastdebug版本openjdk(debug版本的jdk可以输出调试信息,方便分析问题),下载地址fastdebug

    2.准备测试代码

    1.  
      public static void log(String msg){
    2.  
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    3.  
        System.out.println(sdf.format(new Date())+" "+msg);
    4.  
      }
    5.  
       
    6.  
      public static void  displayMemoryInfo(){
    7.  
        log("======memory info start=======");
    8.  
        MemoryMXBean mmbean = ManagementFactory.getMemoryMXBean();
    9.  
        List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
    10.  
        for(MemoryPoolMXBean bean : pools){
    11.  
         System.out.println(bean.getName()+"="+bean.getUsage());
    12.  
        }
    13.  
        log("======memory info end=======");
    14.  
       
    15.  
      }
    16.  
       
    17.  
      public static void testCMSInitiatingOccupancyFraction() throws Exception{
    18.  
         log("a1 allocate start ");
    19.  
         List<byte[]> list = new ArrayList<>(3);
    20.  
         byte a1[]  = new byte[5*_1MB];//a1内存直接分配到eden区,此时eden区内存占用5m+
    21.  
         list.add(a1);
    22.  
         log(" a1 allocated,sleep 4s");
    23.  
         displayMemoryInfo();
    24.  
         Thread.sleep(4000);
    25.  
       
    26.  
         log("a2 allocate start ");
    27.  
         byte a2[]  = new byte[5*_1MB];//由于a1占用了eden 5m+内存,剩余内存不足以容纳a2,
    28.  
                                     //此时会触发ygc,因为s0和s1都不足以容纳a1,所以a1直接晋升到老年代,
    29.  
                                     //然后将a2分配到年轻代,老年代当前内存占用5m+,年轻代当前内存占用5m+
    30.  
         list.add(a2);
    31.  
         log(" a2 allocated,sleep 4s");
    32.  
         displayMemoryInfo();
    33.  
         Thread.sleep(4000);
    34.  
       
    35.  
         log("a3 allocate start ");
    36.  
         byte a3[]  = new byte[10*_1MB];
    37.  
         list.add(a3);
    38.  
         log(" a3 allocated,exit it");//直接分配到老年代,老年代当前15M+
    39.  
         displayMemoryInfo();
    40.  
         Thread.sleep(10000);
    41.  
         System.exit(0);
    42.  
      }
    43.  
       

    3.整个堆30m,年轻代10m,eden 8m,so/s1 1m 4.测试代码搭配的jvm参数

    1.  
      java -verbose:gc -Xms30M -Xmx30M -Xmn10M -XX:+PrintGCDetails  -XX:+PrintGCTimeStamps  -XX:SurvivorRatio=8 -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=80  -XX:+UseConcMarkSweepGC -XX:+PrintTenuringDistribution  -XX:+PrintHeapAtGC  -XX:+PrintGC -XX:+PrintCMSInitiationStatistics -XX:CMSWaitDuration=3000 -XX:+Verbose coding4fun.jvm.TestCMS > testCMSInitiatingOccupancyFraction.log
    2.  
       

    我设置了CMSInitiatingOccupancyFraction=80,CMSWaitDuration=3000,意味着cms gc线程每3s执行一次,如果检测到老年代内存占用率达到80%,那么就触发垃圾收集。

    预期分析

    1.构造a1对象,a1是一个5m的字节数组;2.睡眠4s,等待cms gc 线程执行;3.cms gc线程执行,此时老年代空间利用率为0,不应该触发垃圾收集;4.构造a2对象,a2是一个5m的字节数组,由于eden区空间不足,这时导致a1直接晋升到老年代,此时老年代内存占用5m+;5.睡眠4s; 6.cms gc线程执行,此时老年代空间占用率为20%+,依然小于CMSInitiatingOccupancyFraction,不应该触发垃圾收集;7.构造a3对象,a3是一个10m的字节数据,由于大于eden区空间,所以直接分配到老年代,此时老年代内存占用15m+;8.睡眠10s;9.cms gc线程执行,此时老年代空间利用率为75%+,依然小于CMSInitiatingOccupancyFraction,不应该触发垃圾收集;

    以上是我结合理论知识对cms gc行为的一个预测,下一步我试图结合真实的gc log来验证结果是否符合预期。

    通过gc日志验证猜想

    gc日志比较长,我截取其中一部分:

    1.  
      2020-05-29 14:59:46 a1 allocate start 
    2.  
      2020-05-29 14:59:46  a1 allocated,sleep 4s
    3.  
      ###1 a1 分配完以后打印内存信息,此时eden区内存占用6980K,old区空着
    4.  
      2020-05-29 14:59:46 ======memory info start=======
    5.  
      Code Cache=init = 2555904(2496K) used = 2514048(2455K) committed = 2555904(2496K) max = 251658240(245760K)
    6.  
      Metaspace=init = 0(0K) used = 4624072(4515K) committed = 4980736(4864K) max = -1(-1K)
    7.  
      Compressed Class Space=init = 0(0K) used = 458088(447K) committed = 524288(512K) max = 1073741824(1048576K)
    8.  
      Par Eden Space=init = 8388608(8192K) used = 7148216(6980K) committed = 8388608(8192K) max = 8388608(8192K)
    9.  
      Par Survivor Space=init = 1048576(1024K) used = 0(0K) committed = 1048576(1024K) max = 1048576(1024K)
    10.  
      CMS Old Gen=init = 20971520(20480K) used = 0(0K) committed = 20971520(20480K) max = 20971520(20480K)
    11.  
      2020-05-29 14:59:46 ======memory info end=======
    12.  
       
    13.  
      ###2 cms gc 线程第一次执行(属于jvm的debug信息,使用fastdebug版本的jdk才能输出,这也是我选用fastdebug版本jdk做测试的原因),
    14.  
      ###因为不满足触发条件所以没有触发cms收集过程
    15.  
      ### openjdk 代码位置ConcurrentMarkSweepGeneration::promotion_attempt_is_safe
    16.  
      CMS: promo attempt is safe: available(20971520) >= av_promo(0),max_promo(7148216)
    17.  
       
    18.  
      2020-05-29 14:59:50 a2 allocate start 
    19.  
      TwoGenerationCollectorPolicy::mem_allocate_work: attempting locked slow path allocation
    20.  
      DefNewGeneration::allocate_from_space(655362):  will_fail: false  heap_lock: locked  free: 1048576  should_allocate_from_space: NOT
    21.  
        returns NULL
    22.  
      {Heap before GC invocations=0 (full 0):
    23.  
       par new generation   total 9216K, used 6980K [0x00000000fe200000, 0x00000000fec00000, 0x00000000fec00000)
    24.  
        eden space 8192K,  85% used [0x00000000fe200000, 0x00000000fe8d12b8, 0x00000000fea00000)
    25.  
        from space 1024K,   0% used [0x00000000fea00000, 0x00000000fea00000, 0x00000000feb00000)
    26.  
        to   space 1024K,   0% used [0x00000000feb00000, 0x00000000feb00000, 0x00000000fec00000)
    27.  
       concurrent mark-sweep generation total 20480K, used 0K [0x00000000fec00000, 0x0000000100000000, 0x0000000100000000)
    28.  
       Metaspace       used 4515K, capacity 4638K, committed 4864K, reserved 1056768K
    29.  
        class space    used 447K, capacity 462K, committed 512K, reserved 1048576K
    30.  
      4.491: [GC (Allocation Failure) Allocated 0 objects, 0 bytes concurrently4.492: [ParNewlevel=0 invoke=1 size=5242896CMS: promo attempt is safe: available(20971520) >= av_promo(0),max_promo(7148216)
    31.  
       
    32.  
      Desired survivor size 524288 bytes, new threshold 1 (max 15)
    33.  
      - age   1:    1038272 bytes,    1038272 total
    34.  
      7148216->1048568(9437184), 0.0052765 secs] 7148216->6324312(30408704)Promoted 97 objects, 5265264 bytes Contiguous available 15530664 bytes , 0.0054440 secs] [Times: user=0.00 sys=0.00, real=0.01 secs] 
    35.  
      Heap after GC invocations=1 (full 0):
    36.  
       par new generation   total 9216K, used 1023K [0x00000000fe200000, 0x00000000fec00000, 0x00000000fec00000)
    37.  
        eden space 8192K,   0% used [0x00000000fe200000, 0x00000000fe200000, 0x00000000fea00000)
    38.  
        from space 1024K,  99% used [0x00000000feb00000, 0x00000000febffff8, 0x00000000fec00000)
    39.  
        to   space 1024K,   0% used [0x00000000fea00000, 0x00000000fea00000, 0x00000000feb00000)
    40.  
       concurrent mark-sweep generation total 20480K, used 5152K [0x00000000fec00000, 0x0000000100000000, 0x0000000100000000)
    41.  
       Metaspace       used 4515K, capacity 4638K, committed 4864K, reserved 1056768K
    42.  
        class space    used 447K, capacity 462K, committed 512K, reserved 1048576K
    43.  
      }
    44.  
       
    45.  
      ### 3 这里为什么会触发一次呢?上一次是49s触发,理论上来讲应该在52s左右触发,估计得看源码
    46.  
      CMS: promo attempt is safe: available(15695776) >= av_promo(5275744),max_promo(6291464)
    47.  
       
    48.  
      ###4 a2 分配完以后打印内存信息,此时eden区内存占用5219K,old区占用5152K
    49.  
      2020-05-29 14:59:50  a2 allocated,sleep 4s
    50.  
      2020-05-29 14:59:50 ======memory info start=======
    51.  
      Code Cache=init = 2555904(2496K) used = 2517568(2458K) committed = 2555904(2496K) max = 251658240(245760K)
    52.  
      Metaspace=init = 0(0K) used = 4624936(4516K) committed = 4980736(4864K) max = -1(-1K)
    53.  
      Compressed Class Space=init = 0(0K) used = 458088(447K) committed = 524288(512K) max = 1073741824(1048576K)
    54.  
      Par Eden Space=init = 8388608(8192K) used = 5345200(5219K) committed = 8388608(8192K) max = 8388608(8192K)
    55.  
      Par Survivor Space=init = 1048576(1024K) used = 1048568(1023K) committed = 1048576(1024K) max = 1048576(1024K)
    56.  
      CMS Old Gen=init = 20971520(20480K) used = 5275744(5152K) committed = 20971520(20480K) max = 20971520(20480K)
    57.  
      2020-05-29 14:59:50 ======memory info end=======
    58.  
       
    59.  
      ###5 cms gc 线程第二次执行,由上面Heap after GC日志可以看出此时old区内存占用率为5152/20480=25%,依然不满足触发条件
    60.  
      CMS: promo attempt is safe: available(15695776) >= av_promo(5275744),max_promo(6393768)
    61.  
      2020-05-29 14:59:54 a3 allocate start 
    62.  
      TwoGenerationCollectorPolicy::mem_allocate_work: attempting locked slow path allocation
    63.  
      DefNewGeneration::allocate_from_space(1310722):  will_fail: false  heap_lock: locked  free: 8  should_allocate_from_space: NOT
    64.  
        returns NULL
    65.  
      2020-05-29 14:59:54  a3 allocated,exit it
    66.  
      2020-05-29 14:59:54 ======memory info start=======
    67.  
      Code Cache=init = 2555904(2496K) used = 2527680(2468K) committed = 2555904(2496K) max = 251658240(245760K)
    68.  
      Metaspace=init = 0(0K) used = 4626464(4518K) committed = 4980736(4864K) max = -1(-1K)
    69.  
      Compressed Class Space=init = 0(0K) used = 458088(447K) committed = 524288(512K) max = 1073741824(1048576K)
    70.  
      Par Eden Space=init = 8388608(8192K) used = 5345200(5219K) committed = 8388608(8192K) max = 8388608(8192K)
    71.  
      Par Survivor Space=init = 1048576(1024K) used = 1048568(1023K) committed = 1048576(1024K) max = 1048576(1024K)
    72.  
      CMS Old Gen=init = 20971520(20480K) used = 15761520(15392K) committed = 20971520(20480K) max = 20971520(20480K)
    73.  
      2020-05-29 14:59:54 ======memory info end=======
    74.  
       
    75.  
      ###6 cms gc 线程第三次执行,由上面Heap after GC日志可以看出此时old区内存占用率为15761520/20971520=75%,依然不满足触发条件,但是却触发了cms gc
    76.  
      CMS: promo attempt is not safe: available(5210000) < av_promo(5275744),max_promo(6393768)
    77.  
      CMSCollector: collect because incremental collection will fail 10.498: [GC (CMS Initial Mark) 10.498: [
    78.  
      checkpointRootsInitialWork, 0.0015329 secs]
    79.  
      [1 CMS-initial-mark: 15761520(20971520)] 22155288(30408704), 0.0017536 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
    80.  
      10.500: [CMS-concurrent-mark-start]
    81.  
      10.500: [CMS-concurrent-mark: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
    82.  
      10.500: [CMS-concurrent-preclean-start]
    83.  
       (modUnionTable: 0 cards)10.500: [CMS-concurrent-preclean: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
    84.  
      10.500: [CMS-concurrent-abortable-preclean-start]
    85.  
      CMS: promo attempt is not safe: available(5210000) < av_promo(5275744),max_promo(6393768)
    86.  
      10.500: [CMS-concurrent-abortable-preclean: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
    87.  
      10.500: [GC (CMS Final Remark) [YG occupancy: 6243 K (9216 K)]10.500: [checkpointRootsFinalWork10.500: [Rescan (parallel) , 0.0015643 secs]10.502: [refProcessingWork10.502: [weak refs processing, 0.0000342 secs]10.502: [class unloading, 0.0010723 secs]10.503: [scrub symbol table, 0.0006146 secs]10.504: [scrub string table, 0.0001729 secs], 0.0019787 secs], 0.0049316 secs][1 CMS-remark: 15761520(20971520)] 22155288(30408704), 0.0050250 secs] [Times: user=0.01 sys=0.00, real=0.01 secs] 
    88.  
      10.505: [CMS-concurrent-sweep-start]
    89.  
      Collected 25 objects, 3144 bytes
    90.  
      Live 73 objects,  15747896 bytes  Already free 123 objects, 5220480 bytes
    91.  
      Total sweep: 20971520 bytes
    92.  
      Statistics for BinaryTreeDictionary:
    93.  
      ------------------------------------
    94.  
      Total Free Space: 633548
    95.  
      Max   Chunk Size: 630611
    96.  
      Number of Blocks: 3
    97.  
      Av.  Block  Size: 211182
    98.  
      Tree      Height: 3
    99.  
      10.506: [CMS-concurrent-sweep: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
    100.  
       
    101.  
      MetaspaceGC::compute_new_size: 
    102.  
          minimum_free_percentage:   0.40  maximum_used_percentage:   0.60
    103.  
           used_after_gc       : 4864.0KB
    104.  
          maximum_free_percentage:   0.70  minimum_used_percentage:   0.30
    105.  
          minimum_desired_capacity: 21296.0KB  maximum_desired_capacity: 21296.0KB
    106.  
       
    107.  
      From compute_new_size: 
    108.  
        Free fraction 0.248582
    109.  
        Desired free fraction 0.400000
    110.  
        Maximum free fraction 0.700000
    111.  
        Capactiy 20971
    112.  
        Desired capacity 26263
    113.  
        Younger gen size 9437
    114.  
        unsafe_max_alloc_nogc 5044
    115.  
        contiguous available 5044
    116.  
        Expand by 5292440 (bytes)
    117.  
      Expanded CMS gen for Free ratio
    118.  
        Expanded free fraction 0.248582
    119.  
      10.506: [CMS-concurrent-reset-start]
    120.  
      10.506: [CMS-concurrent-reset: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
    121.  
       
    122.  
      ###7 周期性触发cms gc线程
    123.  
       15761520->15758376(20971520)CMS: promo attempt is not safe: available(5213144) < av_promo(5275744),max_promo(6393768)
    124.  
      CMSCollector: collect because incremental collection will fail 13.506: [GC (CMS Initial Mark) 13.506: [
    125.  
      checkpointRootsInitialWork, 0.0015626 secs]
    126.  
      [1 CMS-initial-mark: 15758376(20971520)] 22152144(30408704), 0.0017226 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
    127.  
      13.508: [CMS-concurrent-mark-start]
    128.  
      13.508: [CMS-concurrent-mark: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
    129.  
      13.508: [CMS-concurrent-preclean-start]
    130.  
       (modUnionTable: 0 cards)13.509: [CMS-concurrent-preclean: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
    131.  
      13.509: [CMS-concurrent-abortable-preclean-start]
    132.  
      CMS: promo attempt is not safe: available(5213144) < av_promo(5275744),max_promo(6393768)
    133.  
      13.509: [CMS-concurrent-abortable-preclean: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
    134.  
      13.509: [GC (CMS Final Remark) [YG occupancy: 6243 K (9216 K)]13.509: [checkpointRootsFinalWork13.509: [Rescan (parallel) , 0.0015383 secs]13.510: [refProcessingWork13.510: [weak refs processing, 0.0000320 secs]13.511: [class unloading, 0.0014836 secs]13.512: [scrub symbol table, 0.0006510 secs]13.513: [scrub string table, 0.0001597 secs], 0.0024201 secs], 0.0048316 secs][1 CMS-remark: 15758376(20971520)] 22152144(30408704), 0.0048838 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
    135.  
      13.514: [CMS-concurrent-sweep-start]
    136.  
      Collected 0 objects, 0 bytes
    137.  
      Live 73 objects,  15747896 bytes  Already free 79 objects, 5223624 bytes
    138.  
      Total sweep: 20971520 bytes
    139.  
      Statistics for BinaryTreeDictionary:
    140.  
      ------------------------------------
    141.  
      Total Free Space: 634511
    142.  
      Max   Chunk Size: 630611
    143.  
      Number of Blocks: 6
    144.  
      Av.  Block  Size: 105751
    145.  
      Tree      Height: 5
    146.  
      13.514: [CMS-concurrent-sweep: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
    147.  
       
    148.  
      MetaspaceGC::compute_new_size: 
    149.  
          minimum_free_percentage:   0.40  maximum_used_percentage:   0.60
    150.  
           used_after_gc       : 4864.0KB
    151.  
          maximum_free_percentage:   0.70  minimum_used_percentage:   0.30
    152.  
          minimum_desired_capacity: 21296.0KB  maximum_desired_capacity: 21296.0KB
    153.  
       
    154.  
      From compute_new_size: 
    155.  
        Free fraction 0.248582
    156.  
        Desired free fraction 0.400000
    157.  
        Maximum free fraction 0.700000
    158.  
        Capactiy 20971
    159.  
        Desired capacity 26263
    160.  
        Younger gen size 9437
    161.  
        unsafe_max_alloc_nogc 5044
    162.  
        contiguous available 5044
    163.  
        Expand by 5292440 (bytes)
    164.  
      Expanded CMS gen for Free ratio
    165.  
        Expanded free fraction 0.248582
    166.  
      13.514: [CMS-concurrent-reset-start]
    167.  
      13.514: [CMS-concurrent-reset: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
    168.  
      Heap
    169.  
       par new generation   total 9216K, used 6243K [0x00000000fe200000, 0x00000000fec00000, 0x00000000fec00000)
    170.  
        eden space 8192K,  63% used [0x00000000fe200000, 0x00000000fe718fb0, 0x00000000fea00000)
    171.  
        from space 1024K,  99% used [0x00000000feb00000, 0x00000000febffff8, 0x00000000fec00000)
    172.  
        to   space 1024K,   0% used [0x00000000fea00000, 0x00000000fea00000, 0x00000000feb00000)
    173.  
       concurrent mark-sweep generation total 20480K, used 15389K [0x00000000fec00000, 0x0000000100000000, 0x0000000100000000)
    174.  
       Metaspace       used 4524K, capacity 4638K, committed 4864K, reserved 1056768K
    175.  
        class space    used 448K, capacity 462K, committed 512K, reserved 1048576K
    176.  
      ClassLoaderData CLD: 0x0000000015895070, loader: 0x00000000feb00000, loader_klass: 0x000000010000fa50 sun/misc/Launcher$ExtClassLoader { claimed  handles 0x000000001576a350
    177.  
      metaspace: 0x00000000158da150
    178.  
       

    从gc日志里我写的注释可以看到**###6 cms gc 线程第三次执行,由上面Heap after GC日志可以看出此时old区内存占用率为15761520/20971520=75%,依然不满足触发条件,但是却触发了cms gc**不满足我之前的第9条预期,带着疑问接下来结合gc日志和openjdk源码尝试解答这个问题。

    再看gc日志

    1.  
      CMS: promo attempt is not safe: available(5210000) < av_promo(5275744),max_promo(6393768)
    2.  
      CMSCollector: collect because incremental collection will fail 10.498: [GC (CMS Initial Mark) 10.498: [
    3.  
      checkpointRootsInitialWork, 0.0015329 secs]
    4.  
      [1 CMS-initial-mark: 15761520(20971520)] 22155288(30408704), 0.0017536 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
    5.  
      10.500: [CMS-concurrent-mark-start]
    6.  
      10.500: [CMS-concurrent-mark: 0.000/0.000 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
    7.  
      10.500: [CMS-concurrent-preclean-start]
    8.  
       

    其实日志的开头2行已经说明了原因,只是我知识面比较浅薄不知道cms gc触发不仅仅是“老年代占用率达到CMSInitiatingOccupancyFraction”这一个条件,从日志信息初判是因为老年代剩余空间小于平均晋升大小导致(CMS: promo attempt is not safe: available(5210000) < av_promo(5275744),max_promo(6393768) CMSCollector: collect because incremental collection will fail),这里扯个题外话,正常版本的jdk是打印不出来这种debug信息的,强烈建议下载debug版本的jdk学习jvm,当遇到阻碍的时候根据debug信息去网络上搜索会得到更有价值的信息。

    结合日志看源码

    "CMSCollector: collect because incremental collection will fail"是在concurrentMarkSweepGeneration.cpp中shouldConcurrentCollect方法输出的,简单读一下源码:

    1. 如果发生了full gc会触发,看下面日志是调用了System.gc或者gc_locker(这个没明白是什么场景)

    1.  
      //如果发生了full gc,看下面日志是调用了System.gc或者gc_locker(这个没明白是什么场景)
    2.  
        if (_full_gc_requested) {
    3.  
          if (Verbose && PrintGCDetails) {
    4.  
            gclog_or_tty->print_cr("CMSCollector: collect because of explicit "
    5.  
                                   " gc request (or gc_locker)");
    6.  
          }
    7.  
          return true;
    8.  
        }
    9.  
       

    2.如果没有指定UseCMSInitiatingOccupancyOnly参数,jdk就按自己的规则来决定老年代当前的利用率是否会触发gc,这里分两种情况: 2.1 根据历史数据做预测,如果cms执行完gc需要的时间大于老年代被填满的时间那就触发gc,具体的判断逻辑在time_until_cms_start中; 2.2 没有历史数据的时候判断老年代利用率是否大于_bootstrap_occupancy,_bootstrap_occupancy是根据CMSBootstrapOccupancy计算出来的

    1.  
      // If the estimated time to complete a cms collection (cms_duration())
    2.  
        // is less than the estimated time remaining until the cms generation
    3.  
        // is full, start a collection.
    4.  
       
    5.  
        /**如果没有指定UseCMSInitiatingOccupancyOnly参数,jdk就按自己的规则来决定老年代当前的利用率是否会触发gc
    6.  
        分两种情况:
    7.  
            1.根据历史数据做预测,如果cms执行完gc需要的时间大于老年代被填满的时间那就触发gc,具体的判断逻辑在time_until_cms_start中
    8.  
            2.没有历史数据的时候判断老年代利用率是否大于_bootstrap_occupancy,_bootstrap_occupancy是根据CMSBootstrapOccupancy计算出来的
    9.  
            _bootstrap_occupancy = ((double)CMSBootstrapOccupancy)/(double)100,CMSBootstrapOccupancy是一个可传递参数,默认值为50
    10.  
        */
    11.  
        if (!UseCMSInitiatingOccupancyOnly) {
    12.  
          //cms gc 只要被触发一次stats().valid()就会返回true
    13.  
          if (stats().valid()) {
    14.  
            if (stats().time_until_cms_start() == 0.0) {
    15.  
              return true;
    16.  
            }
    17.  
          } else {
    18.  
             //下面的这段逻辑只会被触发一次
    19.  
       
    20.  
            // We want to conservatively collect somewhat early in order
    21.  
            // to try and "bootstrap" our CMS/promotion statistics;
    22.  
            // this branch will not fire after the first successful CMS
    23.  
            // collection because the stats should then be valid.
    24.  
            if (_cmsGen->occupancy() >= _bootstrap_occupancy) {
    25.  
              if (Verbose && PrintGCDetails) {
    26.  
                gclog_or_tty->print_cr(
    27.  
                  " CMSCollector: collect for bootstrapping statistics:"
    28.  
                  " occupancy = %f, boot occupancy = %f", _cmsGen->occupancy(),
    29.  
                  _bootstrap_occupancy);
    30.  
              }
    31.  
              return true;
    32.  
            }
    33.  
          }
    34.  
        }
    35.  
       

    3.执行ConcurrentMarkSweepGeneration::should_concurrent_collect判断逻辑,分以下几种情况: 3.1 老年代利用率大于_initiating_occupancy会触发gc,_initiating_occupancy的值在CMSCollector被构造的时候通过CMSInitiatingOccupancyFraction计算出来; 3.2 发生了扩容需要触发gc; 3.3 _cmsSpace(CompactibleFreeListSpace)->should_concurrent_collect(这块没看明白)。

    1.  
      // Otherwise, we start a collection cycle if
    2.  
        // old gen want a collection cycle started. Each may use
    3.  
        // an appropriate criterion for making this decision.
    4.  
        // XXX We need to make sure that the gen expansion
    5.  
        // criterion dovetails well with this. XXX NEED TO FIX THIS
    6.  
        if (_cmsGen->should_concurrent_collect()) {
    7.  
          if (Verbose && PrintGCDetails) {
    8.  
            gclog_or_tty->print_cr("CMS old gen initiated");
    9.  
          }
    10.  
          return true;
    11.  
        }
    12.  
       
    1.  
      bool ConcurrentMarkSweepGeneration::should_concurrent_collect() const {
    2.  
       
    3.  
        assert_lock_strong(freelistLock());
    4.  
        //老年代利用率大于initiating_occupancy
    5.  
        if (occupancy() > initiating_occupancy()) {
    6.  
          if (PrintGCDetails && Verbose) {
    7.  
            gclog_or_tty->print(" %s: collect because of occupancy %f / %f  ",
    8.  
              short_name(), occupancy(), initiating_occupancy());
    9.  
          }
    10.  
          return true;
    11.  
        }
    12.  
        if (UseCMSInitiatingOccupancyOnly) {
    13.  
          return false;
    14.  
        }
    15.  
       
    16.  
        //发生了扩容
    17.  
        if (expansion_cause() == CMSExpansionCause::_satisfy_allocation) {
    18.  
          if (PrintGCDetails && Verbose) {
    19.  
            gclog_or_tty->print(" %s: collect because expanded for allocation ",
    20.  
              short_name());
    21.  
          }
    22.  
          return true;
    23.  
        }
    24.  
       
    25.  
        //没看明白
    26.  
        if (_cmsSpace->should_concurrent_collect()) {
    27.  
          if (PrintGCDetails && Verbose) {
    28.  
            gclog_or_tty->print(" %s: collect because cmsSpace says so ",
    29.  
              short_name());
    30.  
          }
    31.  
          return true;
    32.  
        }
    33.  
        return false;
    34.  
      }
    35.  
       

    4.执行gch->incremental_collection_will_fail判断逻辑,本质上是预测young gc是否会失败,这里的预测标准有以下几种: 4.1 最近一次已经是失败的; 4.2 最近一次未失败,继续询问年轻代是否会失败(DefNewGeneration::collection_attempt_is_safe()),年轻代的判断逻辑如下:  4.2.1 如果to区不为空,认为收集可能会失败(和to区是否为空有啥关系呢?)   4.2.2 询问老年代晋升是否会失败(ConcurrentMarkSweepGeneration::promotion_attempt_is_safe),老年代判断剩余空间大小是否大于平均晋升空间大小或者大于当前年轻代使用的空间大小;

    1.  
      // We start a collection if we believe an incremental collection may fail;
    2.  
        // this is not likely to be productive in practice because it's probably too
    3.  
        // late anyway.
    4.  
        GenCollectedHeap* gch = GenCollectedHeap::heap();
    5.  
        assert(gch->collector_policy()->is_two_generation_policy(),
    6.  
               "You may want to check the correctness of the following");
    7.  
       
    8.  
        //
    9.  
        if (gch->incremental_collection_will_fail(true /* consult_young */)) {
    10.  
          if (Verbose && PrintGCDetails) {
    11.  
            gclog_or_tty->print("CMSCollector: collect because incremental collection will fail ");
    12.  
          }
    13.  
          return true;
    14.  
        }
    15.  
       
    1.  
      // Returns true if an incremental collection is likely to fail.
    2.  
        // We optionally consult the young gen, if asked to do so;
    3.  
        // otherwise we base our answer on whether the previous incremental
    4.  
        // collection attempt failed with no corrective action as of yet.
    5.  
        bool incremental_collection_will_fail(bool consult_young) {
    6.  
          // Assumes a 2-generation system; the first disjunct remembers if an
    7.  
          // incremental collection failed, even when we thought (second disjunct)
    8.  
          // that it would not.
    9.  
          assert(heap()->collector_policy()->is_two_generation_policy(),
    10.  
                 "the following definition may not be suitable for an n(>2)-generation system");
    11.  
          return incremental_collection_failed() ||
    12.  
                 (consult_young && !get_gen(0)->collection_attempt_is_safe());
    13.  
        }
    14.  
       
    1.  
      bool DefNewGeneration::collection_attempt_is_safe() {
    2.  
        if (!to()->is_empty()) {
    3.  
          if (Verbose && PrintGCDetails) {
    4.  
            gclog_or_tty->print(" :: to is not empty :: ");
    5.  
          }
    6.  
          return false;
    7.  
        }
    8.  
        if (_next_gen == NULL) {
    9.  
          GenCollectedHeap* gch = GenCollectedHeap::heap();
    10.  
          _next_gen = gch->next_gen(this);
    11.  
        }
    12.  
        return _next_gen->promotion_attempt_is_safe(used());
    13.  
      }
    14.  
       
    1.  
      bool ConcurrentMarkSweepGeneration::promotion_attempt_is_safe(size_t max_promotion_in_bytes) const {
    2.  
        size_t available = max_available();
    3.  
        size_t av_promo  = (size_t)gc_stats()->avg_promoted()->padded_average();
    4.  
        bool   res = (available >= av_promo) || (available >= max_promotion_in_bytes);
    5.  
        if (Verbose && PrintGCDetails) {
    6.  
          gclog_or_tty->print_cr(
    7.  
            "CMS: promo attempt is%s safe: available("SIZE_FORMAT") %s av_promo("SIZE_FORMAT"),"
    8.  
            "max_promo("SIZE_FORMAT")",
    9.  
            res? "":" not", available, res? ">=":"<",
    10.  
            av_promo, max_promotion_in_bytes);
    11.  
        }
    12.  
        return res;
    13.  
      }
    14.  
       

    5.判断MetaspaceGC _should_concurrent_collect标识

    1.  
      //5 读取should_concurrent_collect标识
    2.  
            if (MetaspaceGC::should_concurrent_collect()) {
    3.  
            if (Verbose && PrintGCDetails) {
    4.  
            gclog_or_tty->print("CMSCollector: collect for metadata allocation ");
    5.  
            }
    6.  
            return true;
    7.  
          }
    8.  
       
    9.  
        return false;
    10.  
      }
    11.  
       

    云里雾里

    到这儿虽然有一些细节问题我还打着问号,但是也算是解决了心中的疑惑,触发cms gc的条件有好多个,大体归纳为以下几种:1.发生了full gc,比如代码里显示的调用System.gc;2.没有指定UseCMSInitiatingOccupancyOnly参数的时候jvm根据状态数据决定是否要触发gc,大原则就是在老年代填满之前触发gc将空间腾出来;3.老年代利用率达到了CMSInitiatingOccupancyFraction或者老年代发生了扩容等;4.ygc可能不安全,主要还是担心老年代剩余空间不足以容纳晋升对象(我这个小实验中就是因为这个条件触发了cms gc);5.元空间_should_concurrent_collect标识为true;

    总结

    对任何参数的使用一定要经过亲自验证,否则直接应用到生产环境可能会带来不可预料的损失,如果发现和预期效果不一样那就去一步一步证实、论证,在互联网蓬勃发展的今天几乎任何问题都能找到蛛丝马迹,除非自己懒。这里再啰嗦一句,面对信息爆炸的时代如何甄别自己得到的信息是正确的呢?“纸上得来终觉浅,绝知此事要躬行”,多做实验多看源码才是学习的好办法。

  • 相关阅读:
    Flask从负到零的一周
    DOM(一):节点层次-Node类型
    错误处理(三):区分致命错误和非致命错误
    错误处理(二):常见错误类型
    错误处理(一)
    跨域(二)
    跨域(一)
    AJAX(四):XHR2支持的方法
    AJAX(三):GET与POST
    AJAX(二):HTTP头部信息
  • 原文地址:https://www.cnblogs.com/telwanggs/p/15064166.html
Copyright © 2011-2022 走看看