Thursday, August 11, 2005

Garbage Collection in JVM

The memory space which had been allocated to an object from the heap, can be reused when it is not being referenced by the original object. This means that once object finished its work, the memory space that had been used by the object can be reclaimed. This whole process of reclaiming memory is known as garbage collection.

Now more technically, the heap is where the objects of a Java program live. Any time you allocate memory with the new, newarray, anewarray, and multianewarray instructions, the memory comes from the heap. The Java language doesn't allow you to free allocated memory directly. Instead, the runtime environment keeps track of the references to each object on the heap, and automatically frees the memory occupied by objects that are no longer referenced this process called garbage collection.

Two type of garbage can be collected one is the pointer which is pointing to non existing memory address other one is memory space which doesn’t have any pointer to reference it. Also the problem with reclamation of memory arises due to restriction on physical memory size.

It can be called as memory recycling because the memory once freed can be used to allocate to new object. For this GC should have some mechanism to check out which are the object memory space not being referenced. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being freed. Finalizer is activity that will check for dirty object. If it is dirty then it will be written back else will simply freed.

GC has to cope with heap i.e. memory compaction or defragmentation of memory. Suppose memory already allocated in some random order from available heap. Now if memory freed which was lying in between some other object’s memory space, then it will be some what similar to OS memory management scenario. Where having enough memory space to allocate it to process doesn’t satisfy whole requirement. But due to no single memory segment available which is big enough to accommodate process, process waits in queue. This same thing can happen in dynamic memory allocation if proper memory compaction methods are not being used.

So it is clear that any garbage collector must do three basic things. First, it must detect garbage objects i.e. unreferenced objects. Second, it must reclaim the heap space used by the garbage objects and make the space available again to the program. Third, it must take care of possible memory fragmentation.