天天看點

Golang GC

一、增量式 GC

​​GC 增量式垃圾回收​​

二、Golang GC

1、簡要總結

The GC runs concurrently with mutator threads, is type accurate (aka precise), allows multiple GC thread to run in parallel. It is a concurrent mark and sweep that uses a write barrier. It is non-generational and non-compacting. Allocation is done using size segregated per P allocation areas to minimize fragmentation while eliminating locks in the common case.
  1. 三色标記
  2. 寫屏障
  3. 并發标記清理
  4. 非分代
  5. 非緊縮

具體算法描述:

​​​mgc.go​​​​Go GC: Prioritizing low latency and simplicity​​

2、注意點

GCPercent

新配置設定記憶體和前次垃圾收集剩下的存活資料的比率達到該百分比時,就會觸發垃圾收集。預設GOGC=100。設定GOGC=off 會完全關閉垃圾收集。runtime/debug包的​​SetGCPercent​​函數允許在運作時修改該百分比。具體函數資訊如下:

func SetGCPercent(percent int) int      

SetGCPercent sets the garbage collection target percentage: a collection is triggered when the ratio of freshly allocated data to live data remaining after the previous collection reaches this percentage. SetGCPercent returns the previous setting. The initial setting is the value of the GOGC environment variable at startup, or 100 if the variable is not set. A negative percentage disables garbage collection.

NextGC

NextGC is the target heap size of the next GC cycle.

The garbage collector’s goal is to keep HeapAlloc ≤ NextGC. At the end of each GC cycle, the target for the next cycle is computed based on the amount of reachable data and the value of GOGC.

盡管有控制器、三色标記等一系列措施.但垃圾冋收器依然有問題需要解決。

模拟場景:服務重新開機,海量用戶端重新連入,瞬間配置設定大量對象,這會将垃圾回收的觸發條件 NextGC 推到一個很大值。而當服務正常後,因活躍對象遠小于該門檻值,造成垃圾回收久久無法觸發.服務程序内就會有大量白色對象無法被回收,造成隐形記憶體洩漏。

同樣的情形也可能時因為某個算法在短期内大量使用臨時對象造成的。

這是就需要垃圾回收器最後的一道保險措施:監控服務 sysmon 每隔 2 分鐘就會檢查一次垃圾回收狀态,如超出 2 分鐘未曾觸發,那就強制執行。

GCPercent與NextGC的關系

Next GC is after we’ve allocated an extra amount of memory proportional to the amount already in use. The proportion is controlled by GOGC environment variable (100 by default). If GOGC=100 and we’re using 4M, we’ll GC again when we get to 8M (this mark is tracked in next_gc variable). This keeps the GC cost in linear proportion to the allocation cost. Adjusting GOGC just changes the linear constant (and also the amount of extra memory used).

個人微信公衆号: