NOTE
1.1 GC
Historical notes on automatic heap-memory reclamation, reference counting, reachability analysis, mark-sweep, mark-compact, copying, and generational GC.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What Is GC?
An automatic memory-reclamation mechanism for heap memory.
2. Why Is GC Needed?
It frees programmers from the work of manually freeing memory.
2.1. Problems with GC
2.1.1. Memory Leaks
2.1.2. STW
3. How Garbage Collection Is Performed
3.1. GC Trigger
Triggered periodically or when memory space is insufficient.
3.2. Garbage Collection
3.2.1. Reference Counting
Each object has a counter. When a variable references it, the counter is incremented by 1; when a reference becomes invalid, it is decremented by 1. When the counter reaches 0, the object is reclaimed.
Advantage: simple and efficient. Disadvantage: cannot solve circular references. A circular reference means object A references object B and object B references object A, while neither A nor B is referenced by any other object.
3.2.2. Reachability Analysis
Starting from GC Roots, traverse the object graph through references. Objects that can be reached are not garbage. GC Roots: global variables, local variables on the stack, and variables in registers.
3.2.2.1. Mark-Sweep
Mark: starting from GC Roots, mark all reachable objects. Unmarked objects are garbage objects. Sweep: remove all unmarked objects. Disadvantage: memory fragmentation (non-contiguous memory space) is produced. When a larger object needs to be allocated, there may not be enough contiguous memory space.
3.2.2.2. Mark-Compact
Mark: starting from GC Roots, mark all reachable objects. Unmarked objects are garbage objects. Compact: move all surviving objects to one side and reclaim the other areas. Advantage: solves the memory-fragmentation problem. Disadvantage: moving objects is relatively costly.
3.2.2.3. Copying
Divide memory space into two parts and use only one part at a time. When it is used up, copy surviving objects to the other part. Advantage: high efficiency and no memory fragmentation. Disadvantage: only half of the space can be used each time.
3.2.2.4. Generational Garbage Collection
Divide memory into the young generation and old generation according to object survival time. The young generation has the characteristic that only a small number of objects survive each collection, so an improved copying algorithm is used. The old generation has the characteristic that many objects survive, so mark-sweep and mark-compact algorithms are used.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub