Junior — Middle
Can you explain how garbage collection works in managed programming languages?
sobes.tech AI
Answer from AI
In managed programming languages such as Java or C#, Garbage Collection (GC) is an automatic process of freeing memory that is no longer used by the program.
The main idea: when objects in memory become unreachable (no references to them from active code), the garbage collector detects and frees the memory occupied by them.
Approximate working mechanism:
- Reachability Tracking: GC starts with root objects (stack, static variables) and marks all objects that can be reached.
- Garbage Identification: objects that are not marked are considered garbage.
- Memory Freeing: memory occupied by garbage is released for reuse.
In Java, for example, there are several GC algorithms (Mark-and-Sweep, Generational GC) that optimize work in terms of time and memory.
Example code where an object becomes a candidate for garbage collection:
public class Example {
public static void main(String[] args) {
Object obj = new Object();
obj = null; // now the object is unreachable and can be collected by GC
System.gc(); // call to the garbage collector (does not guarantee immediate execution)
}
}