Java Garbage Collection essentials

java garbage collection basics

Garbage collection is a major advantage for Java language. It helps you write code with no worries about objects destruction and memory usage.

So, how are Java Object stored in memory? They are all stored inside the Heap. There are 3 main areas in the Heap of JVM:

  • Young generation
  • Old Generation
  • Permanent Generation

java garbage collection basics

Young Generation

When object is created it placed in a special area of Young Gen space called Eden. When Eden gets full, Garbage Collector is called. All objects with no references are deleted as no more needed. Other objects are moved to Survivor Space.

Survivor Space is a couple of containers (S0 and S1) that is used to store young objects. Garbage Collection cycles keep running and objects that lose their references are destroyed inside survivor spaces.

There is a threshold parameter that is used to determine the number of GC cycles needed to move survived object to an Old Generation.

Garbage collection inside the Young Gen is always a “Stop the world event”. It meens that when this event is proceeded all running threads are paused.

Old Generation

Old Gen is the place where Java stores long-living objects. It also has garbage collection events that “clean up” unused objects. By default, this event is also “Stop the world” one but can be configured.

Permanent Generation

PermGen is the space for storing the meta-data. This data describes classes and methods used by application inside JVM.

So, Java objects can go through 2 phases of lifecycle – young and old generation.

Leave a Reply

Be the First to Comment!