This article explain the Garbage Collection in Java, and it’s benefit .and to some extent illustrates it’s work mechanism.
What is Garbage collection:
Garbage collection in Java is the process of automatically freeing heap memory by deleting unused objects that are no longer accessible in the program. It also frees up developers from having to manually manage a program's memory, which, in turn, reduces the potential for memory-related bugs.
Conditions for a garbage collection
Garbage collection occurs when one of the following conditions is true:
The system has low physical memory. The memory size is detected by either the low memory notification from the operating system or low memory as indicated by the host.
The memory that's used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.
The GC.Collect method is called. In almost all cases, you don't have to call this method because the garbage collector runs continuously. This method is primarily used for unique situations and testing.
How Does Garbage Collection in Java works?
Java garbage collection is an automatic process. Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects.
An in-use object, or a referenced object, means that some part of your program still maintains a pointer to that object.
An unused or unreferenced object is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed. Such as :
When we explicitly assign null to the reference variable
When we assign one reference variable to another reference variable
When the reference variable is out of scope then the object referred by that reference variable is unused
Ways for Invoking Garbage Collector (GC)
When the unused object becomes eligible for garbage collection, garbage collector does not destroy them immediately. JVM runs garbage collector whenever it runs low in memory.
There are two methods for requesting JVM to run garbage collector. They are as follows: