How the Go Garbage Collector Works (Tricolor Mark and Sweep)

Go uses a concurrent tricolor mark-and-sweep garbage collector to automatically reclaim unused memory with minimal pause times.

The Go garbage collector uses a concurrent, non-moving, tricolor mark-and-sweep algorithm to automatically reclaim memory. It classifies objects into white (unvisited), gray (visited but not fully processed), and black (fully processed) sets to identify live objects without stopping the world for long periods. During the mark phase, the GC scans roots and gray objects, turning them black; during the sweep phase, it reclaims white objects. You can tune its behavior using GOGC or inspect it via runtime.GC().

import "runtime"

// Force a garbage collection cycle
runtime.GC()

// Set GC trigger percentage (default 100)
runtime.GOMAXPROCS(1) // Example of runtime tuning
// Note: GOGC env var is preferred for production tuning