Friday 30 May 2014

JVM garbage collection in young generation


    Allocating new objects using new operator (almost) always happens in Eden space. But Eden is actually
a stack. When you create new object needing N bytes, single pointer advances by N bytes on that stack and
that's it. Allocating is that fast, no searching for free spot, compacting, whatever.

  Offcourse this stack is not infinite, at some point we'll reach its end, triggering minor GC. Also most likely
multiple objects are already garbage. So what JVM does in minor GC is the following:



  • Traverse graph of objects starting from GC roots.
  • Copy all objects reachable from GC roots to one of survivor spaces (no gaps, we know all of them
    and this 
    is a single process)

  •  Wipe out eden space (basically just moving this stack pointer back to 0)

In subsequent minor collections there are additional steps:

one of survivor spaces is examined as well. Live objects from both eden and one of survivor spaces are
copied to second survivor space. This means there is always exactly one free survivor space.

So how are objects ending in tenured generation?

  1. First young objects are copied to one of survivor spaces. 
  2. Then they are copied to the other and again and again. Once given object jumps back and forth
    too many 
    times (configurable, 8 by default), it is promoted to tenured space.
  3. Major GC runs when tenured space is full.

No comments:

Post a Comment