GC垃圾回收(2)- 常見的垃圾回收器

Garbage Collectors.png

JDK誕生 Serial追隨 提高效率,誕生了Parallel Scavenge,為了配合CMS,誕生了ParNew,CMS是1.4版本后期引入,CMS是里程碑式的GC,它開啟了并發(fā)回收的過程,但是CMS毛病較多,因此目前沒有任何一個JDK版本默認是CMS。

并發(fā)垃圾回收是因為無法忍受STW

1. Serial & Serial Old

Serial & Serial Old分別是新生代和老年代的垃圾回收器,串行回收,現(xiàn)在一般不用了。

Serial

a stop-the-world(STW),copying collector which uses a single GC thread.

單CPU效率最高 虛擬機是Client模式的默認垃圾回收器。

單線程的,當(dāng)進行垃圾回收時會禁止其它一切操作(STW),它不是立刻停止,會找到一個safe point,一個安全點禁止。

由于Serial收集器進行垃圾回收時的等待時間,即STW時間較長,所以只適合在內(nèi)存空間較小的情況下使用

Serial Old

a stop-the-world(STW),mark-sweep-compact collector that uses a single GC thread.

用于老年代的垃圾收集器,采用標記清除或整理算法

2. Parallel Scavenge & Parallel Old

現(xiàn)在常用的是這兩種收集器的組合,簡稱PS+PO,默認的也是這兩種。多線程進行回收

Parallel Scavenge
年輕代 并行回收

a stop-the-world(STW),copying collector which uses multiple GC threads.

Parallel Old

a compacting collector that uses miltiple GC threads.
使用整理算法

3. ParNew & CMS

ParNew
年輕代 配合CMS的并行回收,是Parallel Scavenge的變種

  • a stop-the-world,copying collector which uses multiple GC threads.
  • It differs from "Parallel Scavenge" in that it has enhancements that make it usable with CMS.
  • For example,"ParNew" does the synchronization needed so that it can run during the concurrent phases of CMS.

默認線程數(shù)為CPU核數(shù)

3.1 CMS

ConcurrentMarkSweep 老年代 并發(fā)的, 垃圾回收和應(yīng)用程序同時運行,降低STW的時間(200ms) CMS問題比較多,所以現(xiàn)在沒有一個版本默認是CMS,只能手工指定 CMS既然是MarkSweep,就一定會有碎片化的問題,碎片到達一定程度,CMS的老年代分配對象分配不下的時候,使用SerialOld 進行老年代回收 想象一下:
PS + PO --> 加內(nèi)存 換垃圾回收器 --> PN + CMS + SerialOld(幾個小時 - 幾天的STW) 幾十個G的內(nèi)存,
單線程回收 --> G1 + FGC 幾十個G --> 上T內(nèi)存的服務(wù)器 ZGC

  • concurrent mark sweep
  • a mostly concurrent,low-pause collector.
  • phases
    1 initial mark
    2 concurrent mark
    3 remark
    4 concurrent sweep

垃圾回收線程和工作線程同時進行

CMS的四個階段如下:


CMS的四個階段.png

初始標記對GC roots進行標記,程序運行時對新產(chǎn)生的垃圾并發(fā)標記,重新標記:對并發(fā)標記時漏掉的或新增的垃圾進行標記(產(chǎn)生STW),最后并發(fā)清理,清理時產(chǎn)生的新垃圾為浮動垃圾,交給下一輪處理。

3.1.1 CMS缺點

CMS的問題

  1. Memory Fragmentation 內(nèi)存碎片化

-XX:+UseCMSCompactAtFullCollection -XX:CMSFullGCsBeforeCompaction 默認為0 指的是經(jīng)過多少次FGC才進行壓縮

當(dāng)碎片化內(nèi)存裝不下其他對象時,會使用Serial Old進行標記整理

  1. Floating Garbage 浮動垃圾

Concurrent Mode Failure
產(chǎn)生:if the concurrent collector is unable to finish reclaiming the unreachable objects before the tenured generation fills up, or if an allocation cannot be satisfiedwith the available free space blocks in the tenured generation, then theapplication is paused and the collection is completed with all the applicationthreads stopped

解決方案:降低觸發(fā)CMS的閾值

PromotionFailed

解決方案類似,保持老年代有足夠的空間

–XX:CMSInitiatingOccupancyFraction 92% 可以降低這個值,讓CMS保持老年代足夠的空間

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容