Java Garbage Collection

What is garbage collection

Garbage collection (GC) in Java refers to the automatic process of memory management. In Java, objects are created on the heap, and when some of them are unreferenced/unreachable, garbage collectors will collect them and free up memories. There are four ways in Java to make objects unreachable and ready for the GC:

  1. Nullifying the reference variable
  2. Re-assigning the reference variable
  3. Object created inside method
  4. Island of isolation – a group of objects that referencing each other but not referenced by any active objects in the application.

Notably, JVM runs GC and we cannot expect when it does. However, we can request JVM for GC, but it provides no guarantee that GC will run.

  1. Make the objects eligible for GC following methods that are mentioned above.
  2. Override finalize() in the class because the garbage collector calls finalize() on the object before destroying it.
  3. Use System.gc() or equivalently Runtime.getRuntime().gc() to request GC.

How does GC work

The heap memory in Java.

As shown above, the heap is divided into three sections:

Young generation

It’s further divided into Eden, S0, and S1 (size ratio 8:1:1). Initially all new objects, except large objects will be created in Tenured generation directly to avoid massive copying in young generation, will be created in Eden, and both S0 and S1 are empty. When Eden is full, a minor GC happens, surviving objects will be moved to S0. Then another minor GC will happen when Eden is full again, and surviving objects from Eden and S0 will be moved to S1, and Eden and S0 will be emptied. Note that now S1 contains objects from Eden and S0, but with different ages – ages increase after each minor GC. Then S0 and S1 switch roles: on the next minor GC, surviving objects will be moved from Eden and S1 to S0, with object aging accordingly (promotion). When objects’ ages exceed certain threshold, they will be moved to the tenured generation.

Tenured generation

Objects that are moved from young generation are stored here. When objects in this section are collected during GC, it’s a major GC.

Permanent generation

Metadata including classes and methods are stored here.

GC algorithms

Some of the most-common GC algorithms:

Mark-Sweep

Mark all unreferenced objects and sweep them.
Cons: It’s inefficient as it pauses the program, and also would generate memory fragments.

Copying

Copy all referenced objects into another area.
Pros: Efficient as it’s only copying referenced objects; no fragments as it will ‘compact’ the objects.
Cons: Waste one half of the memory.

Mark-Compact

Mark all unreferenced objects and compact them.

Garbage collectors

TO-DO

Reference

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments