Junior — Middle
How does the automatic memory cleanup mechanism determine the need to delete objects?
sobes.tech AI
Answer from AI
The automatic memory cleanup mechanism (Garbage Collector) in Java determines the need to delete objects based on whether they are reachable from root references. If an object is not accessible through any references from active threads, call stacks, static fields, or other roots, it is considered unreachable and eligible for deletion.
Main approaches:
- Mark and Sweep: GC traverses all roots, marks reachable objects, then deletes all unreachable ones.
- Reference counting: Objects with a zero reference count are deleted (but this method is rarely used due to issues with cyclic references).
Example:
Object obj = new Object();
obj = null; // now the object is unreachable and can be collected by GC
Thus, GC automatically frees memory, preventing leaks.