Garbage Collection in Java is an automatic memory management process that removes or reclaims unused objects.
In contrast, C language requires manual allocation and deallocation of memory. Java, however, handles memory deallocation automatically through the garbage collector.
Essentially, automatic garbage collection involves examining the heap memory to identify which objects are still in use and which are not, and then deleting the unused objects to free up memory.
Working of Garbage Collector
To determine which objects are no longer in use, the JVM intermittently use the Mark and Sweep algorithm.
It consists of two steps.
Step 1: Marking
In this step, the Garbage collector identifies the used and unused objects and mark the used object.
Step 1: Sweep
In this step, all unused objects are identified and deleted. The heap memory previously occupied by these unused objects is then freed and made available for future use.
Advantages of Garbage Collection
- Automatic Deallocation: Garbage collection enhances memory efficiency in Java by automatically managing memory.
- Reduced Programmer Burden: Programmers do not need to manually handle memory deallocation, as it is automatically managed by the garbage collector.
There are several ways to make an object eligible for garbage collection.
- Nullifying the reference variable:
For example:
1 2 |
Address address=new Address(); address=null; |
2. Assigning a reference to another:
For example :
1 2 3 4 |
Address address1=new Address(); Address address2=new Address(); address1=address2; // Now address one will be available for garbage collection. |
3. Anonymous object:
Example:
1 |
new Address(); |
finalize()
Method:
- Before destroying an object, the Garbage Collector calls the
finalize()
method on the object to perform any necessary cleanup activities. - Once the
finalize()
method completes, the Garbage Collector proceeds to destroy the object. - The
finalize()
method is defined in theObject
class.
System.gc()
Method:
- An object eligible for garbage collection may not be immediately collected; its destruction depends on when the Garbage Collector runs.
- While the exact timing of Garbage Collection cannot be predicted, you can request the JVM to perform garbage collection by calling
System.gc()
. - However, invoking
System.gc()
does not guarantee that the Garbage Collector will run immediately.
Conclusion:
Garbage collection in Java is a crucial feature for automatic memory management, helping to efficiently manage and reclaim memory by removing unused objects. By using the finalize()
method and invoking System.gc()
, you can influence garbage collection, although the exact timing of garbage collection remains unpredictable. Understanding how garbage collection works can improve your application’s performance and memory usage.
Thank you for reading!