Introduction to Garbage Collection
In Java, Garbage Collection (GC) is the process by which Java programs perform automatic memory management.
How Garbage Collection Works
The Garbage Collector operates under a simple premise: if an object can no longer be reached by the running application, it is "garbage" and its memory can be reclaimed.
Generational Garbage Collection
The Garbage Collector does not simply scan the entire heap memory every single time it runs. Scanning gigabytes of memory takes time, and doing it constantly would freeze your application (known as a "Stop-The-World" pause).
Requesting Garbage Collection
As we have established, the Garbage Collector runs automatically in the background. The JVM decides when it is the optimal time to run it (usually when Eden space is getting full).
The finalize() Method
When the Garbage Collector identifies an object as unreachable and decides to destroy it, it doesn't just instantly delete the memory.