Java Garbage Collection

·

2 min read

What is automatic garbage collection?

Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.

Steps of garbage collection

  1. Mark objects as live GC marking.png
  2. Sweep dead objects GCdeletion.png
  3. Compaction GCcompaction.png

How does GC marks the objects as live?

GC1.jpg

What are different spaces/generations in memory?

GC spaces.png

How do live objects move between young, old and permanent generation spaces?

GC lifecycle of objects.jpg

  • live objects are moved into old gen after multiple minor GC cycles defined by tenure and available space in young gen (From and To Space)
  • From Space and To Space are also called survivor spaces (s0, s1)
  • Objects in old gen space are treated as GCRs.
  • For minor GC, references from old gen to young gen are de facto GCR and references from young gen to old gen are ignored
  • Minor GC triggers stop-the-world which pauses the application threads
  • objects which live long enough move from old gen to perm gen

Why generational garbage collection?

As stated earlier, having to mark and compact all the objects in a JVM is inefficient. As more and more objects are allocated, the list of objects grows and grows leading to longer and longer garbage collection time. However, empirical analysis of applications has shown that most objects are short lived.

Here is an example of such data. The Y axis shows the number of bytes allocated and the X access shows the number of bytes allocated over time. whygens.gif

Did you find this article valuable?

Support Udaysinh by becoming a sponsor. Any amount is appreciated!