NOTE
Garbage Collection Algorithms
Mark-sweep, mark-compact, copying, and generational collection.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Mark-Sweep
Garbage collection is divided into two phases:
- Mark: Start from GC Roots and mark all reachable objects. Unmarked objects are garbage objects.
- Sweep: Reclaim all unmarked objects.
1.1. Characteristics
- It creates memory fragmentation (non-contiguous memory regions). When a large object needs to be allocated, there may not be enough contiguous memory space.
2. Mark-Compact
It is divided into marking and compaction phases.
- Mark: Same as above.
- Compact: Move all surviving objects to one side and reclaim the other area.
2.1. Characteristics
It solves the memory-fragmentation problem, but moving objects is relatively expensive.
3. Copying
Divide the memory space into two regions and use only one region at a time. When it is used up, copy surviving objects to the other memory region.
3.1. Characteristics
High efficiency and no memory fragmentation.
Only half of the space can be used each time.
4. Garbage Collection Algorithm Actually Used by the JVM: Generational Collection
Memory is divided into the young generation and old generation according to object lifetime.
-
The young generation has the characteristic that only a small number of objects survive each collection, so an improved copying algorithm is used.
The improved copying algorithm divides memory into Eden and Survivor regions (8:1:1), so only 10% of the space is wasted.
-
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