Showing posts with label mark and sweep. Show all posts
Showing posts with label mark and sweep. Show all posts

Friday, July 18, 2014

What is Garbage Collection in Java ?

The Garbage collection is automatic memory management mechanism provided by java in order to reclaim memory occupied by ideal objects or objects which are no longer used in our program. Garbage collector frees programmer from manually dealing with memory de-allocation. The Garbage Collector is a demon thread which starts running automatically as soon as we execute program. So java program in execution, consists of two threads main thread and garbage collector thread. Garbage collection internally uses finalize() method of object which gives a chance to reclaim any type of resources hold by the object. We can manually call garbage collection using System.gc() but since we do not know when the object needs to be reclaimed and when the object is not in use. Manually calling System.gc() is just a hint to JVM that garbage collection is needed.

Generally Garbage collection internally runs mark and sweep algorithm which is two phase procedure.

Phase 1: Mark
The first phase in garbage collection is marking. GC will mark all the objects as alive, ideal and not referenced. It will internally create the graph of alive and ideal objects.
All the alive objects are directly reachable from the root objects. As long as object is referenced, it is marked as alive. The objects those are referenced but are not used for long time are marked as ideal and the remaining objects are marked as not referenced.

Phase 2: Sweep/Compact
In this phase, GC actually starts reclaiming the objects memory. First it will reclaim the memory of all the objects which are not referenced. Now if any class wants to create new object and if sufficient memory is not available in that case GC will look for ideal objects and will reclaim their memory. If the objects are ideal and sufficient memory is available for creating more objects then garbage collector will not reclaim ideal objects memory.

Here GC moves all the alive objects to the bottom of heap and leaves free space at the top of heap. As objects are moved, the pointers to these objects become invalid, so GC corrects these pointers and helps to solve memory fragmentation problem.