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).

个人微信公众号:
这里写图片描述

作者:jiankunking 出处:http://blog.csdn.net/jiankunking

你可能感兴趣的:(Go,GC,Golang,进阶)