Sobes.tech
Middle+

Tell me about the garbage collector in Go language.

sobes.tech AI

Answer from AI

Go uses a concurrent, tri-color, non-compacting garbage collector with low latency.

Main principles:

  • Mark: Determines which objects are reachable from root pointers (registers, goroutine stacks, global variables). Uses a tri-color algorithm (white - unvisited, gray - visited but children not checked, black - visited and all children checked).
  • Sweep: Removes unreachable objects (remains white) and frees memory for reuse.

Features:

  • Concurrent: Marking occurs concurrently with user code execution (STW - Stop-The-World phases are very short).
  • Low latency: Designed to minimize pauses in application operation.
  • Non-compacting: Does not move live objects in memory, which can lead to fragmentation but simplifies implementation and speeds up marking/sweeping.

Phases:

  1. Mark assist: User goroutines help the collector during the marking phase when allocating memory.
  2. Marking: Parallel marking of reachable objects.
  3. Mark termination: Short STW phase to finalize marking.
  4. Sweeping: Parallel removal of unreachable objects.

Management:

  • Automatic.
  • Garbage collection thresholds (GC trigger) are controlled via the environment variable GOGC. By default, GOGC=100, meaning collection starts when the heap size doubles relative to the previous cycle.
  • The runtime.GC() function forcibly triggers garbage collection, but its use is not recommended in standard code.
package main

import (
	"runtime"
	"time"
)

func main() {
	// Example of forcing GC (rarely needed)
	runtime.GC()

	// Example of getting GC statistics
	var memStats runtime.MemStats
	runtime.ReadMemStats(&memStats)
	// fmt.Printf("Total memory allocated: %v bytes\n", memStats.TotalAlloc)
}

Advantages:

  • Automatic memory management reduces the likelihood of errors (memory leaks, double frees).
  • Designed for concurrent execution.

Disadvantages:

  • Non-deterministic GC runtime.
  • Possible increased memory consumption compared to manual management.