#928 – How Objects Are Removed from the Managed Heap

The Garbage Collector (GC) manages the portion of virtual memory known as the managed heap, where referenced-typed objects are stored.  When an object is no longer referenced, it is destroyed and its memory made available for other objects.

More specifically:

  • The GC runs when available physical memory is low or when the amount of memory allocated on the heap passes some threshold
  • The GC follows all references to build a list of “reachable” objects
  • For all objects that are no longer reachable
    • If the object has a finalizer, it is marked for finalization (but not collected during this pass of the GC)
    • If the object doesn’t have a finalizer, it is marked for collection
  • Objects not marked for collection are compacted–moved to the start of the heap
  • References to moved objects are updated
  • The pointer to the end of the heap is updated (where new objects are allocated)
Advertisements