NOTE

1.1 GC

Garbage collection automatically reclaims heap memory, reducing the need for manual deallocation. These notes continue with the collection process and related problems.

Garbage Collection / RuntimeCreated Updated 2 min readhistorical

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 relieves programmers of having to free memory manually.

2.1. Problems with GC

2.1.1. Memory Leaks

Memory Leak

2.1.2. STW

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. Only a small number of objects in the young generation survive each collection, so it uses an improved copying algorithm. Many objects in the old generation survive collection, so it uses mark-sweep and mark-compact algorithms.

4. GC Tuning

GC Tuning

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub