Golang GC garbage collection mechanism understanding record

1. Concept

The function of automatically recycling memory resources that are no longer in use is called garbage collection (GC: Garbage Collection)

2. Why is there garbage collection?

Programming languages ​​require manual release of memory, which is cumbersome. If not handled properly, memory leaks will occur. The emergence of garbage collection allows developers to focus more on business logic and reduce additional maintenance burdens.

3. Rapid Development of Garbage Recycling

Version

GC algorithm

v1.1

STW(Stop the world)

v1.3

Mark STW, Sweep (mark clear)

v1.5

tricolor marking

v1.8

Three-color marker + write barrier

4. The gc used before go V1.3 is the mark recovery method (mark&sweep)

5. The gc three-color mark used by go V1.5

6. GC trigger conditions

  1. It is triggered when the current memory allocation reaches a certain proportion and exceeds the memory size threshold.

Threshold = last GC memory allocation * memory growth rate

The memory growth rate is controlled by the environment variable GOGC . The default is 100, which means GC is started every time the memory doubles.

  1. By default, GC is triggered once every 2 minutes at most. This interval is declared in the src/runtime/proc.go:forcegcperiod variable. If GC has not been triggered for two minutes, GC will be triggered.

  1. Trigger manually, call runtime.GC()

7. Situations that cannot be GCed

The blocking state is a state scheduled by go to be awakened, and cannot be gc

Common garbage collection methods:

  • Reference counting: Maintain a reference count for each object. When the object referencing the object is destroyed, the reference count is decremented by 1. When the reference counter reaches 0, the object is recycled.
    Advantages: Objects can be recycled quickly and will not be recycled until memory is exhausted or reaches a certain threshold.
    Disadvantages: It cannot handle circular references very well, and there is a certain cost in maintaining reference counts in real time.
    Representative languages: Python, PHP

  • 标记-清除:从根变量开始遍历所有引用的对象,引用的对象标记为"被引用",没有被标记的进行回收。
    优点:解决了引用计数的缺点。
    缺点:需要STW,即要暂时停掉程序运行。
    代表语言:Golang(其采用三色标记法)

  • 分代收集:按照对象生命周期长短划分不同的代空间,生命周期长的放入老年代,而短的放入新生代,不同代有不能的回收算法和回收频率。
    优点:回收性能好
    缺点:实现复杂
    代表语言: JAVA

参考链接:

https://blog.csdn.net/qq_33690342/article/details/113685490

https://studygolang.com/articles/25096

虽然有GC帮我们做内存管理,但资源毕竟是有限的,如果内存持续上涨,说明程序必然有问题。就需要借助性能能分析工具pprof,trace 等工具来分析解决,优化代码或者架构,数据库设计等多个方面来优化。

Guess you like

Origin blog.csdn.net/xia_2017/article/details/128834696