Saturday, January 9, 2016

How Garbage Collection works in Java

Garbage Collection in Java

Garbage collection is a mechanism to reclaim heap memory occupied by those objects which are not being used by any of the live threads of our program. JVM periodically runs a process called Garbage Collector which checks which objects are being used and which are not, and reclaims memories from unused objects and gives it back to the heap memory for future use. Apart from reclaiming memory from unused objects, garbage collector also ensures that objects having live references exist and thus avoids the situation called dangling reference

An object become eligible for garbage collection in the following scenarios:
  •      If the object is assigned a null value like 'object = null', then it becomes eligible for garbage collection.
  •      If a parent object A contains a reference of object B, and if the object A is set to null, then object B also becomes eligible for garbage collection.
  •     If the object is created inside a block and the program control goes out of the scope of the block, then the object becomes eligible for garbage collection.







Here green color represents referenced objects and red color indicates un-referenced ones. Upon moving to survivor space 1, referenced objects get their reference count incremented by one.





In this way, objects continue to get promoted to the old generation because of minor garbage collections. At the end, JVM runs a major garbage collector on the old generation which claims the memories occupied by unused objects and returns it back to the heap memory.

No comments:

Post a Comment