Sobes.tech
Senior

Tell us about the garbage collector in Go. What is tri-color marking? What is a write barrier? What optimizations are used?

sobes.tech AI

Answer from AI

In Go, the garbage collector (GC) is a trigger-based, parallel, concurrent, mark-and-sweep collector with a tri-color marking scheme.

Tri-color marking is an algorithm that divides objects into three groups:

  • White — objects that have not yet been visited and can be collected.
  • Gray — objects that have been visited, but their descendants have not yet been processed.
  • Black — objects that have been visited and all their descendants have also been visited.

GC starts with root objects, marking them gray, then sequentially processes gray objects, marking their descendants, until no gray objects remain. At the end, white objects are considered garbage and are collected.

Write barrier is a mechanism that tracks changes to object references during GC operation to ensure correct marking when the object graph is modified concurrently. In Go, the write barrier helps GC see new references that appear after marking has started, preventing the accidental collection of live objects.

Optimizations in Go GC:

  • Parallel execution of marking and sweeping with minimal pauses.
  • Incremental marking to reduce pause times.
  • Use of write barriers for safety during concurrent access.
  • Efficient memory management and minimization of fragmentation.

This is roughly how GC works in Go, providing a balance between performance and timely memory cleanup.