1. Basic
  • What is GC: a process that looks at Heap memory and identifies which objects are in use and which are not, and deleting the unused objects.
  • Eligibility to be GC: objects that cannot be reached by any ref variable in Stack memory. Those objects can be referred by some other objects but still are unreachable from Stack memory.
  • GC is a Stop-the-World event, means all other threads will be paused when GC occurs.
  • Garbace Collection actually does not "collect the garbage", it collects the "alive" objects and deletes the rest.
2. Generational GC

Generational GC is based on the fact that:

Most of the object dies young.

Heap memory is broken up into smaller parts, each of them is for storing a generation of object:

  • young generation: all new object allocated are stored here and aging. When this space fills up, a minor GC occurs. Due to the high mortality rate, this space is often full of dead object => the GC collect the alive object very quickly.
  • old generation: store long surviving objects. When young generation object's age reach a threshold, they are moved to old generation space. Overtime, this space need to be collected also, this event is called major GC. This event lasts longer because old generation space tends to contain long live object.
  • permanent generation: contains metadata required by the JVM to describe the classes and methods used in the application.

Generation GC process:

  1. New objects are allocated to eden space. Both S0 and S1 space are empty.

2. When Eden space fills up, a minor GC is triggered. Alive objects are moved to S0, dead objects are removed. S1 is still empty.

3. New objects continue to be allocated in Eden, and it fills up again => a minor GC is triggered again. This time, alive objects from Eden and S0 are moved to S1:

After this step, S0 and Eden are empty, all alive objects are in S1.

4. At the next minor GC, the same process repeats. This time, the survivor spaces switch the role

5. When aged object get old enough, they are promoted to Old generation space:

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