JVM garbage collection in young generation

garbage-collectionjvm

Please feel free to correct me if I am wrong. In JVM heap, there are two generations, old and young. When doing full GC, in old generation, there are heavy operations like compact spaces and fixing the hole, which will make JVM hang. And I find in young generation, a light weighted GC is applied, and there are another area called Eden involved in young generation from my search results. However, after search a lot of documents, I still have two confusions about GC in young generation,

  1. In young generation, it seems GC does not work in the way which old generation GC works (i.e. old generation GC compact and fixing the hole)? If so, how did GC in young generation works?
  2. What is Eden space and how this space is utilized in young generation? Appreciate if any document for a newbie could be recommended.

Best Answer

This is the single, most important diagram you have to memorize and understand:

Java memory layout
(source: oracle.com)

It comes from Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning, one stop place to learn everything about GC internals. But to address your immediate questions:

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.

Of course 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? First young objects are copied to one of survivor spaces. 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.

Major GC runs when tenured space is full.

Related Topic