DEV Community

uthman durosinlohun
uthman durosinlohun

Posted on

Understanding Garbage Collection in Java: A Beginner’s Guide

Introduction

Imagine we have a room where we store things such as books, clothes, gadgets. Over time, as we get new things, the old ones pile up, making the room messy and cluttered. Now, what if we had a helpful assistant who regularly checks our room and removes the items you no longer use? It keeps the memory clean by getting rid of unused objects.
When we create objects in our code, they take up memory. The garbage collector identifies objects that are no longer needed and removes them, freeing up memory.

What is Garbage Collection?

Garbage Collection is Java’s way of keeping memory clean and organized. It removes objects that are no longer needed, ensuring that our programs run smoothly without running out of memory.
In languages like C or C++, programmers manually allocate and free memory. This leads to common problems such as memory leaks, accessing freed memory and freeing already freed memory. Java eliminates these problems through automatic garbage collection

How Garbage Collection Works

  1. Marking: The JVM starts from "root" objects (like static variables, local variables in active methods, and active threads) and follows references to identify all reachable objects. This is called marking.
  2. Sweeping: Any objects not marked as reachable are considered garbage and can be removed.
  3. Compacting: The space used by unreachable objects is reclaimed and made available for new objects.

Example in Java

class Student {
    private String name;

    public Student(String name) {
        this.name = name;
    }

    public void display() {
        System.out.println("Student Name: " + name);
    }
}

public class GarbageCollectionDemo {
    public static void main(String[] args) {
        Student student1 = new Student("Alice");
        Student student2 = new Student("Bob");

        student1.display();
        student2.display();

        // Remove references
        student1 = null;
        student2 = null;

        // Request garbage collection
        System.gc();

        System.out.println("Garbage Collection executed.");
    }
}
Enter fullscreen mode Exit fullscreen mode

What Happens Here?

  • We create two student objects.

  • We remove their references by setting them to null, making them eligible for garbage collection.

  • Calling System.gc() requests garbage collection (though the JVM decides when to run it).

Types of Garbage Collectors in Java

Just like different cleaning methods exist for different types of mess, Java provides different garbage collectors:

  1. Serial Garbage Collector: Single-threaded, simple but pauses application just like a single cleaner tidying up one room at a time.

  2. Parallel Garbage Collector: Uses multiple workers to clean faster, great for multi-core systems.

  3. CMS (Concurrent Mark-Sweep) Collector: Minimizes pauses by doing most work concurrently

  4. G1 (Garbage First) Collector: Divides heap into regions by first focusing on the messiest parts first thereby optimizing performance.

Memory Leaks in Java

Even with garbage collection, memory leaks can happen if you maintain references to objects you no longer need, typically through:

  • Static fields
  • Unclosed resources (streams, connections)
  • Improper caching
  • Inner class references

Conclusion

Java's garbage collection does the heavy lifting of memory management, but understanding how it works changes how we write code. The choice between collectors isn't just technical, it shapes our application's performance under pressure. While the JVM handles the cleanup, the most effective Java developers still craft their code with memory patterns in mind. This balance between automation and thoughtful design is what makes Java both accessible and powerful, even as applications grow increasingly complex.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay