Mark & Sweep Algorithm
InfoOne of the Garbage Collection techniques,
it is a method of reclaiming memory by finding objects in memory that are no longer referenced.
Mark
Starting from root objects, find and mark all reachable objects.
- Object Creation: Mark as 0
- Graph traversal from all roots: Mark as 1
Root Objects
In garbage collection, they serve as the "starting point" and are a set of objects directly accessible by the program.
- Variables on the stack
- Global objects and variables
- Values stored in registers
Sweep
Remove unmarked objects (i.e., objects that are no longer reachable) from memory.
- Clean up objects marked as 0
- Initialize the marking bit of all objects (it will be changed back to 1 in the Mark phase)
Disadvantages
- The program's execution is temporarily suspended while garbage collection is performed.
- Fragmentation problem occurs
- Available memory space is split, requiring defragmentation.