DEV Community

Mohammed mhanna
Mohammed mhanna

Posted on

🧹 Garbage Collection (GC) in Java

Have you ever wondered who cleans up the objects you stop using in Java?
The answer: The Garbage Collector (GC) β€” one of Java’s most powerful features that manages memory automatically.

Let’s explore what it is, how it works, and why it’s so important πŸ‘‡


🧠 What Is Garbage Collection?

Garbage Collection is the process of automatically freeing memory by removing objects that are no longer reachable in your program.

In simpler terms β€” Java’s GC looks for objects your code no longer uses and deletes them to make space for new ones.

Example:

public class Main {
    public static void main(String[] args) {
        String name = new String("Mohammed");
        name = null; // The old object becomes unreachable
        System.gc(); // Suggests garbage collection
    }
}

Enter fullscreen mode Exit fullscreen mode

Here, the "Mohammed" object becomes garbage when name no longer references it.


🧩 Why Do We Need Garbage Collection?

In languages like C or C++, developers must manually allocate and free memory.
But in Java, the GC automatically handles that for you.

Without GC:

❌ Memory leaks
❌ Dangling pointers
❌ Manual cleanup headaches

With GC:

βœ… Automatic memory management
βœ… Safer and cleaner programs
βœ… Fewer memory-related bugs

In short β€” GC allows you to focus on logic, not memory management.


βš™οΈ How Does the Garbage Collector Work?

Java’s memory is divided into two main areas:

  1. Heap β†’ Where objects are created.

  2. Stack β†’ Where references and method calls live.

The GC focuses on the heap.

Here’s a simplified process:

  • The GC marks all objects that are still reachable.
  • It identifies objects that are not reachable anymore.
  • It cleans up (deletes) the unreachable objects.
  • It may compact memory to make allocation faster.
  • This process is automatic, but it happens behind the scenes.

πŸͺ„ When Does Garbage Collection Happen?

You can suggest GC to run using:

System.gc();

Enter fullscreen mode Exit fullscreen mode

…but remember β€” this is just a request, not a command.
The JVM decides when to actually perform garbage collection, based on memory pressure and usage.


πŸ” How the JVM Knows What to Collect

The GC uses a concept called reachability:

An object is reachable if it can still be accessed through:

  • A local variable in a method
  • A static field
  • Another reachable object

If none of these point to it, the object is unreachable β†’ it becomes garbage.

Example:

class Car {
    String name;
    Car(String name) { this.name = name; }
}

public class Main {
    public static void main(String[] args) {
        Car c1 = new Car("BMW");
        Car c2 = new Car("Audi");
        c1 = null; // BMW object now unreachable
    }
}
Enter fullscreen mode Exit fullscreen mode

βœ… The "Audi" object is still reachable through c2.
πŸ—‘ The "BMW" object is garbage and will be collected eventually.


🚦 Different Garbage Collectors in Java

Java has multiple GC algorithms (you can choose based on your use case):

  • Serial GC β€” best for single-threaded applications.
  • Parallel GC β€” uses multiple threads for faster collection.
  • G1 GC (Garbage First) β€” default in modern JVMs; balances performance and pause time.
  • ZGC & Shenandoah β€” advanced low-latency collectors for large-scale apps.

You can specify which GC to use with JVM flags, for example:

java -XX:+UseG1GC MyApp

Enter fullscreen mode Exit fullscreen mode

🧭 Best Practices for Working with GC

πŸ’‘ 1. Avoid unnecessary object creation
Reuse objects where possible to reduce GC pressure.

πŸ’‘ 2. Null out references you no longer need
Especially for large data structures.

πŸ’‘ 3. Prefer local variables
They are collected faster since they go out of scope quickly.

πŸ’‘ 4. Use profiling tools
Monitor memory usage using tools like:

  • VisualVM
  • JConsole
  • Java Mission Control

πŸ’‘ 5. Don’t rely too heavily on System.gc()
Let the JVM handle GC automatically.


πŸ”¬ Understanding the Lifecycle

  1. Object created β†’ in Heap.

  2. Reference lost β†’ becomes unreachable.

  3. Marked as garbage β†’ waiting for collection.

  4. Collected by GC β†’ memory reclaimed.


πŸ“˜ Additional Resources

πŸ“™ Official Java Docs: Garbage Collection Tuning Guide (Oracle)

🧰 VisualVM Tool β€” to analyze GC activity in real time.


πŸ’¬ Questions for you

Have you ever faced memory leaks in Java despite using GC?

Do you manually call System.gc() in any of your projects?

Which GC algorithm have you experimented with β€” G1, ZGC, or Parallel?


Top comments (0)