The Go Garbage Collector combines the following approaches:

  1. Concurrency
  2. Tri-colour marking
  3. Mark and sweep

The garbage collector is triggered based on the GOGC assigned.

Write barriers

The Go garbage collector ensures that when a pointer that references a white pointer is written to a black object, that (white) object will be marked as a grey object to prevent premature sweeping.

  • Prevents race conditions and allows the program to run concurrently

Phases of a Garbage Collection Cycle

  1. Setup
  2. Mark
  3. Mark Termination
  4. Sweep

The mark termination phase first ensures that all goroutines reach a garbage collection safepoint. Next, the garbage collection will stop all goroutines and then scan remaining grey objects in the heap and the stack.

  • Mark termination is the only phase that is not concurrent - as the garbage collector implements a stop-the-world pause

Concurrency and Parallelism

The go garbage collector is able to be concurrent and parallel (except when mark termination occurs).

When the objects in the heap are being scanned, the heap-space is divided into tasks to be processed by the kernel threads. Theses heap scanning tasks can be “stolen” by idle threads (see work stealing).

See also