The Go Garbage Collector combines the following approaches:
- Concurrency
- Tri-colour marking
- 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
- Setup
- Mark
- Mark Termination
- 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
- Stack resizing and shrinking
- Heap Growth Ratio
- Finalisers - used by the garbage collector for non-memory resources