Sobes.tech
Middle+

How does the garbage collector work in Go (tri-color marking)?

sobes.tech AI

Answer from AI

The garbage collector in Go uses the tri-color marking algorithm to efficiently detect and remove unused objects.

Main idea:

  • All objects on the heap are divided into three colors:
    • White — objects that have not yet been checked and are considered potential garbage.
    • Gray — objects that are discovered as reachable, but their children have not yet been checked.
    • Black — objects that are reachable and all their children have been checked.

Process:

  1. Initially, all objects are white.
  2. Root objects are marked gray and added to a queue.
  3. While the queue is not empty, take a gray object, mark it black, and for each of its child objects, if they are white, mark them gray and add them to the queue.
  4. After the traversal is complete, all white objects are considered unreachable and are removed.

In Go, the garbage collector works concurrently with the application, minimizing pauses. The tri-color marking helps avoid issues with changing the object graph during the collector's operation.

This allows for efficient and safe memory freeing without stopping the program for a long time.