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;
}

你可能感兴趣的:(ZGC源码分析(3)- ZGC触发的时机)