Middle
What is a garbage collector and how does it work?
sobes.tech AI
Answer from AI
Garbage Collector (GC) is an automatic memory management mechanism that allocates and frees memory no longer used by the program.
Working principles:
- Memory allocation: When the program creates objects, the garbage collector allocates space for them in the heap.
- Reachability determination: The GC determines which objects are accessible from the 'roots' of the program. Roots can be local variables, static variables, references from threads, etc.
- Garbage collection: Objects that are unreachable from the roots are considered 'garbage' and their memory can be freed.
Various algorithms include:
- Mark-and-Sweep: The collector marks reachable objects and then sweeps the heap to free unmarked objects.
- Copying: The heap is divided into two parts; reachable objects are copied from one to the other, and the old part is cleared.
- Generational: Objects are divided into generations; new objects go to the young generation, old to the mature. Collection occurs more frequently in the young generation.
Example in Java (simplified):
// Program creates objects in heap
Object obj1 = new Object();
Object obj2 = new Object();
// obj1 becomes unreachable
obj1 = null;
// GC may free memory occupied by obj1