Sobes.tech
Middle+

How does the garbage collector work in the Go programming language?

sobes.tech AI

Answer from AI

The garbage collector in Go is based on a mark-and-sweep algorithm triggered by memory allocation. It runs concurrently with the main program and minimizes pauses.

Key points:

  • Three sets of colors:
    • White: Objects that have not been visited and are potentially garbage.
    • Gray: Objects accessible from roots but not yet scanned.
    • Black: Objects accessible from roots and already scanned.
  • Marking: The collector starts from roots (global variables, each goroutine's stack), marking accessible objects as gray. It then recursively scans gray objects, marking reachable ones as gray, and scanned objects become black.
  • STW (Stop-The-World) phase during marking: A brief pause of all goroutines at the start of marking to create a snapshot of the object graph and at the end to switch states.
  • Concurrent marking: Most of the marking is performed concurrently with program execution.
  • Sweep: After marking, all remaining white objects are considered unreachable and are freed. Go does not require explicit pointer nullification.
// Example: when an object becomes unreachable
 type Data struct {
    value int
}

func main() {
    d1 := &Data{value: 10} // Object created, accessible
    _ = d1                 // Using the object

    d1 = nil // Object is no longer reachable from variable d1.
            // Garbage collector can free it in the next cycle.

    // Other objects that are not referenced by anyone can also be collected.
}
  • Trigger: The collector is triggered when the allocated memory exceeds a certain threshold, which depends on the previous allocated memory. By default, this threshold is twice the previous memory usage.
  • Goal: Maintain low latency by avoiding long "Stop-The-World" pauses.
// Garbage collector behavior can be controlled via environment variables
// For example, setting GOGC=off disables garbage collection.

Overall, Go's garbage collector is efficient and requires minimal developer intervention.