How Garbage Collection Really works
All objects are allocated on the heap area managed by the JVM. Every item that the developer uses is treated this way, including class objects, static variables, and even the code itself. As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.
Garbage Collector root
- Local variables in the main method
- The main thread
- Static variables of the main class
Mark and Sweep Algorithm
- The algorithm traverses all object references, starting with the GC roots, and marks every object found as alive.
- All of the heap memory that is not occupied by marked objects is reclaimed. It is simply marked as free, essentially swept free of unused objects.
- When objects are no longer referenced directly or indirectly by a GC root, they will be removed. There are no classic memory leaks.