Garbage Collector
1. Overview
1.1. Definition:
- A garbage collector (GC) is a form of automatic memory management. The system is responsible for identifying and reclaiming memory that is no longer in use by programs, thus preventing memory leaks.
1.2. Purpose:
- The primary objective of garbage collection is to free up memory space that is no longer needed, enabling efficient memory usage in processes that dynamically manage memory allocation and deallocation during runtime.
1.3. Mechanism:
- Reachability: Typically, a GC determines object eligibility for garbage collection based on reachability; objects that cannot be reached by any reference path from a root reference are considered garbage.
- Phases: Common GC processes include marking, sweeping, compacting, and possibly copying.
- Marking: Traverses object graphs starting from root references to mark all reachable objects.
- Sweeping: Reclaims memory occupied by unmarked (non-reachable) objects.
- Compacting: Reorganizes objects in memory to reduce fragmentation and improve allocation performance.
- Copying: Moves reachable objects to a new memory area and reclaims the old area as free space.
1.4. Types:
- Reference Counting: Counts references to each object and collects objects once references reach zero.
- Tracing Garbage Collection: Uses graph traversal techniques (mark-and-sweep, mark-and-compact, generational) to discover unused objects.
- Generational GC: Optimizes for the observation that most objects die young by segregating them into different lifespan generations.
Tags::programming: