Golang & Concurrency (50 Qs)•Part 1: Go Language Core, Memory & Runtime Internals (1 - 15)
How does Go's Garbage Collector work (Concurrent Tri-Color Mark and Sweep)?
senior LevelMemory Management
In Simple Words: Go employs a non-generational, concurrent, tri-color mark-and-sweep collector optimized for low latency (sub-millisecond STW pauses) rather than raw batch throughput:
- Tri-Color Abstraction:
- White: Unvisited objects (candidates for reclamation).
- Grey: Visited objects whose referenced children haven't been visited yet.
- Black: Visited objects whose references have all been scanned (reachable, retained).
- Execution Phases:
- Sweep Termination (Brief STW < 100µs): Prepares the mark phase, activates the write barrier.
- Concurrent Mark: GC worker goroutines traverse object graphs alongside application goroutines. If an application mutates a pointer during marking, the Write Barrier catches it to prevent reachable objects from being collected.
- Mark Termination (Brief STW < 100µs): Finalizes root sets and turns off the write barrier.
- Concurrent Sweep: Unused memory is returned to the runtime free lists concurrently.
- Tuning: Configured via
GOGC(default 100 = triggers GC when heap grows by 100%) andGOMEMLIMIT(hard memory cap to prevent OOM kills in Kubernetes pods).