The Algorithm of Garbage Collection
Garbage collector makes sure if a particular memory block should to be freed by examining if it is occupied by the garbage objects application will no longer consume.
Every application owns a collection of pointers to memory address. Each entry in the collection is usually called as root. A root is actually a particular pointer to the block of memory region which is occupied by certain garbage object which should not be released. Theses objects include: global reference variables and static reference variables, all local variables and parameter variables in thread stack in a method, and the CPU register to a reference variables. When compiling a particular IL code, the JIT compiler will generate an internal table which stores not only the byte offset of each CPU instruction but also the all the roots in their scope.
When garbage collector begins to execution of garbage collection, it assumes firstly that all objects allocated in managed heap can be garbage collected. In other word, it assumes that each of the objects allocated in managed heap is not be referred in a particular root. Then garbage collector scans each of the roots, and then draws a graphic which contains the entire objects referred directly or indirectly by the roots recursively. The objects contained in the graphic are all called as reachable objects since all the objects are reachable from the roots. All the reachable objects can be considered as the ones which should not currently be garbage collected. At the point, garbage collector can make distinct garbage object from the reachable objects.
After making sure all the objects which can be garbage collected, the garbage collector then scans the managed heap to seek for a block of contiguous memory region occupied by garbage objects and the small memory region will be let alone. If such a contiguous memory region is found out, garbage collector will remove some non-garbage objects into it. Obviously, the former pointers to the objects become invalid, so garbage collector must revise the root and make them to re-point to the objects correctly, and all the pointers to the objects will be revised as well.