GC4_Semi_Space

collector_type.h文件中关于枚举值kCollectorTypeSS有这样一句注释来介绍它:“Semi-space/mark-sweep hybrid,enables compaction."。其含义是SemiSpace综合了Semi-space(即Copying Collector)和Mark-Sweep方法,同时还支持压缩。而kCollectorTypeGSS则是支持分代回收的SS方法。

纵观SemiSpace,它的GC逻辑无非就是如下两点。

  • 对GSS而言,from_space_中能搜索到的对象将被“提升”到promo_dest_space_空间中。对SS而言,from_space_中能搜索到的对象拷贝到to_space_中。GC之后,from_space_的空间被回收。
  • 其他空间的处理和MarkSweep的类似,按照集合Live和集合Mark来找到和释放垃圾对象即可。SemiSpace在ART中的作用很重要,我们下文介绍应用程序退到后台后,虚拟机为减少内存碎片而做的内存压缩时就会用到它。

semi_space.cc

RunPhases

void SemiSpace::RunPhases() {
    Thread* self = Thread::Current();
    InitializePhase();//①回收器初始化
    //if为true,说明mutator线程已被暂停。这种情况的出现和SemiSpace的用法有关,
    //我们暂且不用考虑这些
    if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
        MarkingPhase();//②标记工作
        ReclaimPhase();//回收工作,非常简单,留给读者自行研究
    } else {
        //如果mutator未暂停,则SemiSpace只有标记阶段需要暂停mutator
        {
            ScopedPause pause(this);//暂停mutator
            MarkingPhase();//标记工作
        }
            {//mutator恢复运行,可同时开展回收工作
            ReaderMutexLock mu(self, *Locks::mutator_lock_);
            ReclaimPhase();
        }
    }
    FinishPhase();
}