In: Computer Science
Explain the reference count garbage collection and its disadvantages. How are the disadvantages handled?
Reference counting (refcounting) GC is one of the two primary GC mechanisms widely used. The basic workings of this GC is pretty simple and based on counting the number of reference to a memory block (or object) from other blocks. Each time memory is created or a reference to the object is assigned it’s refcount is bumped up. Each time a pointer is assigned away from it the refcount is reduced. When refcount of the block goes to 0, it means that no pointer references it and hence it is un-reachable and is garbage and can be reclaimed.
Let’s assume RefCount(VOID *pMem) gives us the reference count of the object at pMem. Then the following code shows how the reference count of a specific object in memory varies with the code flow.
Object * obj1 = new Object(); // RefCount(obj1) starts at 1 Object * obj2 = obj1; // RefCount(obj1) incremented to 2 as new reference is added Object * obj3 = new Object(); obj2->SomeMethod(); obj2 = NULL; // RefCount(obj1) decremented to 1 as ref goes away obj1 = obj3; // RefCount(obj1) decremented to 0 and can be collected
As the execution flow mutates the state of the program, the refcount of each object is updated transparently and the block is freed when refcount hits 0.
A disadvantage of reference counting is that it does not detect cycles. A cycle is two or more objects that refer to one another. Another disadvantage is the overhead of incrementing and decrementing the reference count each time. Because of these disadvantages, reference counting currently is out of favor.