How golang garbage collection works

It is a Mark-and-Sweep GC.

Phases

  1. Mark

    1. Stop-the-World: Set write barrier (to know how much was allocated during maark phase)
    2. Concurrent: Mark all memory which is still in use by the app
    3. Stop-the-World: Remove write barrier
  2. Concurrent: Sweep (it actually happens on new allocations)

Details/Algorithm

It’s a tri-color process: grey for objects to check, black for used objects, white for unused.

Stop the world first — set the write barrier on. All objects are white.
All root objects are marked as grey.
All new objects or all objects having new pointers to are marked as grey from now on.

Concurrent mark.
GC does the BFS traversal: get an object from grey, mark it as black, add all the pointed objects to grey. Continue.

When the process is finished (no grey objects left), another stop the world is done to set the write barrier to off.

Sweep phase removes all white objects (during new allocations).

If the algorithm sees there are too many allocations, it adds more processors to help the concurrent mark phase (mark assistants).

Resources

Algorithm video


https://www.youtube.com/watch?v=n59VtiRx34s

Video from Bill Kennedy (very basic; great explanation of gc trace):

https://www.youtube.com/watch?v=q4HoWwdZUHs

Video from Uber:

https://www.youtube.com/watch?v=q1h2g84EX1M

Similar Posts

LEAVE A COMMENT