ZGC源码分析(3)- ZGC触发的时机

ZGC以被动回收为主,即由后台线程控制何时启动垃圾回收。 ZGC的触发时机在

jdk11/src/hotspot/share/gc/z/zDirector.cpp

ZDirector决定是否要执行GC的后台线程

线程出发的条件是根据一个自定义的时钟。

void ZDirector::run_service() {
  // Main loop
  while (_metronome.wait_for_tick()) {
    sample_allocation_rate();
    const GCCause::Cause cause = make_gc_decision();
    if (cause != GCCause::_no_gc) {
      ZCollectedHeap::heap()->collect(cause);
    }
  }
}
GCCause::Cause ZDirector::make_gc_decision() const {
  // Rule 0: Timer
  if (rule_timer()) {
    return GCCause::_z_timer;
  }

  // Rule 1: Warmup
  if (rule_warmup()) {
    return GCCause::_z_warmup;
  }

  // Rule 2: Allocation rate
  if (rule_allocation_rate()) {
    return GCCause::_z_allocation_rate;
  }

  // Rule 3: Proactive
  if (rule_proactive()) {
    return GCCause::_z_proactive;
  }

  // No GC
  return GCCause::_no_gc;
}

目前有4种情况可以自动的触发ZGC.

1,基于一个固定时间触发

这个时间可以通过ZCollectionInterval,来控制,缺省值为0,表示不需要。

  product(uint, ZCollectionInterval, 0,                                     \
          "Force GC at a fixed time interval (in seconds)")                 \
bool ZDirector::rule_timer() const {
  if (ZCollectionInterval == 0)      return false;

  // Perform GC if timer has expired.
  const double time_since_last_gc = ZStatCycle::time_since_last();
  const double time_until_gc = ZCollectionInterval - time_since_last_gc;

  return time_until_gc <= 0;
}

2,预热规则触发

指的是当Hotspot刚启动时,当发现heap使用率达到整个堆的10/20/30%,并且其他类型的GC都还没执行时,会主动地触发GC。当其他类型的GC出发后,会判断是否还需要预热,如果需要继续执行,不需要则不再执行。预热的的条件是 GC发生的次数不超过3次。

bool ZDirector::is_warm() const {
  return ZStatCycle::ncycles() >= 3;
}

bool ZDirector::rule_warmup() const {
  if (is_warm()) {
    // Rule disabled
    return false;
  }

  // Perform GC if heap usage passes 10/20/30% and no other GC has been
  // performed yet. This allows us to get some early samples of the GC
  // duration, which is needed by the other rules.
  const size_t max_capacity = ZHeap::heap()->current_max_capacity();
  const size_t used = ZHeap::heap()->used();
  const double used_threshold_percent = (ZStatCycle::ncycles() + 1) * 0.1;
  const size_t used_threshold = max_capacity * used_threshold_percent;

  log_debug(gc, director)("Rule: Warmup %.0f%%, Used: " SIZE_FORMAT "MB, UsedThreshold: " SIZE_FORMAT "MB",
                          used_threshold_percent * 100, used / M, used_threshold / M);

  return used >= used_threshold;
}

3,根据分配速率

在这里使用到正态分布,我们在代码里面能看到两个相关的应用:根据内存分配的情况估算内存被消耗完还可能要多长时间;根据垃圾回收的时间估算进行一次垃圾回收的时间。

在G1中我们介绍到垃圾回收时间的估算使用的是衰减平均(Decaying Average),它是一种简单的数学方法,用来计算一个数列的平均,核心是给近期的数据更高的权重,即强调近期数据对结果的影响。衰减平均计算公式如下:

image.png

式中 ɑ 为历史数据权值,1−ɑ 为最近一次数据权值。即 ɑ 越小,最新的数据对结果影响越大,最近一次的数据对结果影响最大。不难看出,其实传统的平均就是 ɑ 取值为 (n−1)/n 的情况。具体可以参考《JVM G1源码分析和调优》

ZGC中主要是基于正态分布来估算,学过概率论的同学大都知道这一概念。为了读懂这段代码,我们先来回顾一下正态分布。首先它是一条中间高,两端逐渐下降且完全对称的钟形曲线。图形形状为:

image.png

正态分布也非常容易理解,它指的大多数数据应该集中在中间附近,少数异常的情况才会落在两端。
对于垃圾回收算法中的数据:内存的消耗时间,垃圾回收的时间也应该符合这样的分布。注意,并不是说G1中的停顿预测模型不正确或者效果不好;而是说使用正态分布来做预测有更强的数学理论支撑。在使用中ZGC还是对这个数学模型做了一些改变。
通常使用N表示正态分布,假设X符合均值为μ方差为σ2的分布,做数学变换令Y = (X - μ)/ σ则它符合N(0, 1)分布。如下所示:


image.png

假设已知内存分配的时间符合正态分布,我们可以获得抽样数据,从而估算出内存分配所需时间的均值和方差。这个均值和方差是我们基于样本数据估算得到的,它们可能和实际真实的均值和方差有一定的误差。所以如果我们直接使用这个均值和方差可能由样本数据波动导致不准确,所以在概率论中引入了置信度和置信区间。简单的说置信区间指的是这个参数估计的一段区间,它是这个参数的真实值有一定概率落在测量结果的周围的程度。而置信度指的是就是这个概率。

假定给定一个内存分配花费的时间X1, X2, …, Xn我们想要知道在99.9%的情况下内存分配花费的时间。点估计量符合:

image.png

其中μ为样本均值,σ样本标准差。
对应99.9%置信度,查标准正态分布表得到统计量为3.290527。

image.png

由此可以得到置信区间为
image.png

。所以可以得到最大的内存消耗在满足99.9%的情况下不会超过
image.png

。在ZGC中对这个公司又做了一点修改,实际上是把这个值变得更大:
image.png

。Tolerance缺省值为2,这样的结果使得置信度更高,即远大于99.9%。同理对于垃圾回收的时间也类似处理。理解了置信区间和置信度下面的代码非常简单。
bool ZDirector::rule_allocation_rate() const {
  if (is_first()) {
    // Rule disabled
    return false;
  }

  // Perform GC if the estimated max allocation rate indicates that we
  // will run out of memory. The estimated max allocation rate is based
  // on the moving average of the sampled allocation rate plus a safety
  // margin based on variations in the allocation rate and unforeseen
  // allocation spikes.

  // Calculate amount of free memory available to Java threads. Note that
  // the heap reserve is not available to Java threads and is therefore not
  // considered part of the free memory.
  const size_t max_capacity = ZHeap::heap()->current_max_capacity();
  const size_t max_reserve = ZHeap::heap()->max_reserve();
  const size_t used = ZHeap::heap()->used();
  const size_t free_with_reserve = max_capacity - used;
  const size_t free = free_with_reserve - MIN2(free_with_reserve, max_reserve);

  // Calculate time until OOM given the max allocation rate and the amount
  // of free memory. The allocation rate is a moving average and we multiply
  // that with an allocation spike tolerance factor to guard against unforeseen
  // phase changes in the allocate rate. We then add ~3.3 sigma to account for
  // the allocation rate variance, which means the probability is 1 in 1000
  // that a sample is outside of the confidence interval.
  const double max_alloc_rate = (ZStatAllocRate::avg() * ZAllocationSpikeTolerance) + (ZStatAllocRate::avg_sd() * one_in_1000);
  const double time_until_oom = free / (max_alloc_rate + 1.0); // Plus 1.0B/s to avoid division by zero

  // Calculate max duration of a GC cycle. The duration of GC is a moving
  // average, we add ~3.3 sigma to account for the GC duration variance.
  const AbsSeq& duration_of_gc = ZStatCycle::normalized_duration();
  const double max_duration_of_gc = duration_of_gc.davg() + (duration_of_gc.dsd() * one_in_1000);

  // Calculate time until GC given the time until OOM and max duration of GC.
  // We also deduct the sample interval, so that we don't overshoot the target
  // time and end up starting the GC too late in the next interval.
  const double sample_interval = 1.0 / ZStatAllocRate::sample_hz;
  const double time_until_gc = time_until_oom - max_duration_of_gc - sample_interval;

  log_debug(gc, director)("Rule: Allocation Rate, MaxAllocRate: %.3lfMB/s, Free: " SIZE_FORMAT "MB, MaxDurationOfGC: %.3lfs, TimeUntilGC: %.3lfs",
                          max_alloc_rate / M, free / M, max_duration_of_gc, time_until_gc);

  return time_until_gc <= 0;
}
ZAllocationSpikeTolerance是一个修正系数,

  product(double, ZAllocationSpikeTolerance, 2.0,                           \
          "Allocation spike tolerance factor")                              \

4,自行控制进行GC

heap距离上次GC发生后使用增长率超过10%,或者距离上次GC发生后超过5min。这个参数是弥补第三个条件中没有覆盖的场景,从上述分析可以得到第三个条件更多的覆盖分配速率比较高的场景。

  diagnostic(bool, ZProactive, true,                                        \
          "Enable proactive GC cycles")                                     \
bool ZDirector::rule_proactive() const {
  if (!ZProactive || !is_warm()) {
    // Rule disabled
    return false;
  }

  // Perform GC if the impact of doing so, in terms of application throughput
  // reduction, is considered acceptable. This rule allows us to keep the heap
  // size down and allow reference processing to happen even when we have a lot
  // of free space on the heap.

  // Only consider doing a proactive GC if the heap usage has grown by at least
  // 10% of the max capacity since the previous GC, or more than 5 minutes has
  // passed since the previous GC. This helps avoid superfluous GCs when running
  // applications with very low allocation rate.
  const size_t used_after_last_gc = ZStatHeap::used_at_relocate_end();
  const size_t used_increase_threshold = ZHeap::heap()->current_max_capacity() * 0.10; // 10%
  const size_t used_threshold = used_after_last_gc + used_increase_threshold;
  const size_t used = ZHeap::heap()->used();
  const double time_since_last_gc = ZStatCycle::time_since_last();
  const double time_since_last_gc_threshold = 5 * 60; // 5 minutes
  if (used < used_threshold && time_since_last_gc < time_since_last_gc_threshold) {
    return false;
  }

  const double assumed_throughput_drop_during_gc = 0.50; // 50%
  const double acceptable_throughput_drop = 0.01;        // 1%
  const AbsSeq& duration_of_gc = ZStatCycle::normalized_duration();
  const double max_duration_of_gc = duration_of_gc.davg() + (duration_of_gc.dsd() * one_in_1000);
  const double acceptable_gc_interval = max_duration_of_gc * ((assumed_throughput_drop_during_gc / acceptable_throughput_drop) - 1.0);
  const double time_until_gc = acceptable_gc_interval - time_since_last_gc;

  return time_until_gc <= 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353

推荐阅读更多精彩内容