Java (JVM) Garbage Collection


Garbage Collection


JVM runs a GC Demon Thread which periodically frees up memory occupied by non-referenced objects in the Heap. An object is eligible for Garbage Collection if there are no live references of that Object. The behavior of Garbage Collection in JVM differs between different sections of Heap. The Heap is primarily divided into 3 sections:


  1. Young Generation – This is where all new objects are allocated and aged. When the young generation fills up, this causes a minor garbage collection. Some surviving objects are aged and eventually moved to the old generation.
  2. Old Generation – This is used to store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. Eventually the old generation needs to be collected. This event is called a major garbage collection.
  3. Permanent generation – This contains metadata required by the JVM to describe the classes and methods used in the application. It contains the Method Area and String Pool Area. The permanent generation is included in a full garbage collection.
** Major GC is slower than the Minor GC because Major GC involves live Objects.

Object Allocation, Ageing and Garbage Collection

New objects are allocated to the eden space. Both survivor spaces start out empty.




When the eden space fills up, a minor garbage collection is triggered.

Surviving objects from eden space are moved to the first survivor space. Unreferenced objects are deleted when minor garbage collection is triggered in eden space.



At the next minor GC, surviving objects from eden space are moved to the second survivor space along with that Objects from first survivor space are aged and moved to second survivor space. Once all surviving objects have been moved to second survivor space, both first survivor space and eden are cleared



At the next minor GC, the same process repeats. However this time the survivor spaces switch. Referenced objects are moved to first survivor space. Surviving objects are aged. Eden and second survivor space are cleared.



At the next minor GC, aged objects which has reached a certain Threshold are moved to Old Generation



As minor GCs continue to occure objects will continue to be promoted to the old generation space.



Eventually, a major GC will be performed on the old generation which cleans up and compacts that space.



1 comment: