Junior — Middle
How does the garbage collector mechanism decide which objects to delete from memory?
sobes.tech AI
Answer from AI
The garbage collector in Java determines which objects are eligible for removal based on their reachability in memory. If an object is unreachable from root references (such as from the stack, static variables, or registers), it is considered garbage and can be collected.
Main mechanisms:
- Reachability Analysis: The JVM tracks which objects are reachable through chains of references from the roots.
- Generational Garbage Collection: Objects are divided into generations (young, old), which optimizes collection.
- Mark-and-Sweep: Reachable objects are marked first, then unmarked objects are removed.
Thus, the garbage collector automatically frees memory by removing objects that are no longer referenced, preventing memory leaks.