Sobes.tech
Senior

When does the Garbage Collector run? Are there specific stop points or moments?

sobes.tech AI

Answer from AI

In Go, the Garbage Collector (GC) runs automatically when the runtime determines that memory needs to be freed from unused objects. The exact moments of its invocation depend on several factors:

  • Memory usage threshold: GC is triggered when the allocated memory exceeds a certain threshold related to the previous collection cycle.

  • Safepoints: Go uses the concept of safepoints — points where all goroutines are paused so that GC can safely scan memory. These points occur during function calls, system calls, and other places where execution can be safely stopped.

  • Parallel and concurrent GC: In modern versions of Go, GC runs in parallel with program execution, minimizing pauses. It scans the heap and frees memory without fully stopping all goroutines, using mechanisms like write barriers.

  • Manual triggers: You can invoke garbage collection manually via runtime.GC(), but this is rarely necessary.

Thus, GC is triggered automatically as needed, using safepoints for safe goroutine stopping, and operates in parallel with the program to minimize delays.

When does the Garbage Collector run? Are there… - sobes.tech