Updated 6 September 2024
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.
To determine which objects are no longer in use, the JVM intermittently use the Mark and Sweep algorithm.
It consists of two steps.
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
There are several ways to make an object eligible for garbage collection.
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:
finalize()
method on the object to perform any necessary cleanup activities.finalize()
method completes, the Garbage Collector proceeds to destroy the object.finalize()
method is defined in the Object
class.System.gc()
Method:
System.gc()
.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!
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.