Sobes.tech
Junior — Middle

How does the garbage collector in Java free unused memory?

sobes.tech AI

Answer from AI

In Java, the garbage collector (GC) automatically frees memory occupied by objects that are no longer used by the program.

Working principle:

  1. Determining object reachability: GC tracks objects that are no longer referenced from active parts of the program (e.g., from the call stack or static variables).
  2. Marking: All reachable objects are marked as alive.
  3. Cleaning: Objects not marked as alive are considered garbage, and their memory is freed.

Java uses different GC algorithms (e.g., Mark-and-Sweep, Generational GC) that optimize memory management and minimize application pauses.

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

How does the garbage collector in Java free unused… - sobes.tech