Wednesday, December 22, 2010

How Garbage Collection works in Java

Garbage collection is one of the features that made Java very popular, it saved developers the burden of having to deal with pointers. This convenience came at a price though; developers had to give up control over the objects' cleanup, only the JVM can decide when to collect objects.


Heap memory arrangement:
The heap is divided into 3 main spaces:

  1. Young: contains the newly created objects. It usually contains 3 spaces; Eden and 2 survivor spaces that active objects get copied in between.
  2. Tenured: contains old objects.
  3. Perm: it holds data needed by the virtual machine.
The JVM comes with a default arrangement of generations, but you can always change their sizes to fit the requirements of your system.

Collectors:

The collectors mentioned below are stop-the-world "tracing collectors" in which a collector starts from the root reference and follows all the references until all reachable objects have been examined.  
  • Mark-sweep: It marks all the nodes it visits and after it is done, it collects the non-marked ones. It is used to collect objects in the old generation region of the heap.
  • Copying Collectors: When the space of memory dedicated to active objects fills up this collector runs and copies the live objects to another space of the heap and then switch the roles of these two spaces. This type of collectors is used to collect objects in the young generation region of the heap.
Developers have the option of running the collectors above concurrently by using the following flags:

  • -XX:+UseConcMarkSweepGC : enables concurrent collector
  • -XX:+UseParNewGC : enables parallel copying collector
  • XX:UseParallelGC : enables parallel scavenge collector 

For more details, check out these links:
http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html
http://www.javaperformancetuning.com/news/qotm026.shtml
http://www.ibm.com/developerworks/java/library/j-jtp10283/

No comments: