Garbage Collection in Java: What It Is, How It Works & More — Sematext

What is Garbage Collection in Java: A Definition

Object Eligibility: When Does Java Perform Garbage Collection

How to Make an Object Eligible for GC?

public Integer run() { 
Integer variableOne = 10;
Integer variableTwo = 20;
return variableOne + variableTwo;
}

How to Request the JVM to Run GC?

How Does Java Garbage Collection Work?

JVM-based cycle
  • Young data will not survive long
  • Data that is old will continue to persist in memory
  • Young generation which is divided into two sections called Eden space and Survivor space
  • Old generation, or Tenured space.
Java Heap Space
Heap Object Promotion
  • -XX:MetaspaceSize — initial size of the Metaspace memory region,
  • -XX:MaxMetaspaceSize — maximum size of the Metaspace memory region,
  • -XX:MinMetaspaceFreeRatio — minimum percentage of class metadata capacity that should be free after garbage collection,
  • -XX:MaxMetaspaceFreeRatio — maximum percentage of class metadata capacity that should be free after garbage collection.

The Heap Structure of G1 Garbage Collector

G1 GC regions

What Triggers Java Garbage Collection

  • Minor event — happen when the Eden space is full and moved data to Survivor space. So a Minor event happens within the young generation
  • Mixed event — a Minor event plus reclaim of the Tenured generation
  • Full GC event — a young and old generation space clearing together

Java Garbage Collectors Types

Serial Garbage Collector

Parallel Garbage Collector

Concurrent Mark Sweep Garbage Collector

G1 Garbage Collector

Z Garbage Collector

Java Garbage Collection Benefits

Java Garbage Collection Best Practices

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store