Senior
How does the Garbage Collector work in Java?
sobes.tech AI
Answer from AI
Garbage Collector (GC) in Java automatically manages memory by freeing objects that are no longer used by the program. The JVM tracks objects in the heap and determines which ones are unreachable from root references (such as from the stack or static variables). Such objects are considered garbage and are eligible for removal.
Main stages of GC operation:
- Marking: identifying live objects.
- Sweeping: removing unused objects.
- Compacting: compressing memory to reduce fragmentation (in some algorithms).
Java uses different GC algorithms, for example:
- Serial GC — a simple single-threaded collector.
- Parallel GC — multi-threaded for improved performance.
- G1 GC — divides the heap into regions, optimizing pauses.
Example: when an object no longer has references from active code, GC will free its memory to prevent leaks and heap overflow.