What is a Garbage Collector?
1. What is it? #
- A garbage collector (GC), a concept of computer science, simply is a program or process which is run by OS, in order to free some space of the device’s memory which was allocated before and now is not used anymore. In other words, we can say that it is a form of memory management.
- As the previous post, we read about References in OOP and know about a process of cleaning memory. So in some operating systems, GC takes care of that process.
- Let’s move to the next part to see how garbage collector works.
2. How does garbage collector work? #
- Because of the name “Garbage Collector”, many of us usually think that GC finds, collects and cleans all unused objects. On the contrary, GC does the opposite, it finds and marks all live objects which are being used, and then everything else will be cleared away.
- So how does GC know which objects are used or not? GC checks the references of objects from root. If the object have a direct or indirect reference from root, it will be marked as an used object by GC.
- As the picture above, we can see GC starts marking used objects from the root. The objects (in blue) don’t have any references from root will be discarded when GC process starts.
For example, if the object A (also C) has a reference from root, it will be marked as an used object. B has a reference from A, thus, it is supposed to be used as well. Consequently, D is marked as an used object (generally, B and D have an indirect link from root). When a cleanup happens, A, B, C and D will be kept alive and the others will be freed from memory.
Let’s assume that if the reference between A and root is removed, A and B will not be marked as used objects by GC anymore (there is no link from root to them). As a result, D will also become unused. When a cleanup appears, only C will be kept and the others, including A, B, D, will be recycled.

