Sobes.tech
Senior

What is a Garbage Collector?

sobes.tech AI

Answer from AI

Garbage Collector (GC) is a component of the Java runtime environment that automatically manages memory by freeing objects that are no longer in use by the program.

The main task of GC is to detect objects that have no references from active code and free the memory they occupy to prevent leaks and memory overflow.

How it works:

  • The JVM tracks objects in the heap.
  • Periodically, a garbage collection process runs to determine which objects are reachable (alive) and which are not.
  • Unreachable objects are removed, and the memory is returned to the pool for reuse.

Garbage collectors come in different types (e.g., Serial, Parallel, G1, ZGC), which differ in algorithms and strategies, affecting application performance and latency.

Example: if an object is created inside a method and after exiting the method there are no references to it, GC will eventually free the memory occupied by that object.