Home > en > programming > java

Java

Marcos - 03/30/2025

Garbage Collection in Java: Understand How the JVM Manages Memory (With Practical Examples)

Garbage Collection in Java: Learn how the JVM manages memory with practical examples. Understand GC, its collectors, and optimize your code!

Garbage Collection in Java: Understand How the JVM Manages Memory (With Practical Examples)

Hey, how’s it going? If you’ve ever programmed in Java, you’ve definitely heard of Garbage Collection.

But have you ever stopped to think about how it actually works inside the JVM? Today, I’m going to tell you all about this essential mechanism that makes Java so practical and efficient at memory management.

Let’s break it down together, with practical examples so you can visualize how it all happens!

If you’re an intermediate or advanced developer, this chat will help you better understand what’s going on behind the code you write.

And, listen, knowing how the JVM manages memory might even save you from headaches in more complex projects.

Ready to dive in?

What is Garbage Collection in Java?

Imagine you’re writing code and creating objects to solve a problem.

Every object you instantiate takes up space in memory, right? Now, think about this: what happens to those objects when you don’t need them anymore? In languages like C, you’d have to manually free that memory.

But in Java, my friend, that’s where Garbage Collection (or GC, for short) comes in.

The GC is like a “janitor” for the JVM (Java Virtual Machine). It identifies objects that your program isn’t using anymore and frees up the memory they occupy.

That means less work for you and more safety to avoid memory leaks—those infamous issues that can tank your system’s performance.

Why Does the JVM Need Garbage Collection?

The JVM is the heart of Java, and it needs to ensure your program runs smoothly without exhausting the machine’s resources.

When you create an object with the new operator, it goes straight to the heap—a memory area where all objects live. But the heap isn’t infinite, is it?

If no one took care of it, the memory would fill up fast, and your program would crash.

Garbage Collection steps in to solve this problem, cleaning up what’s no longer useful and keeping everything running.

It’s like an automatic inventory control: what’s no longer useful gets cleared out to make room for what matters.

How Does Garbage Collection Work in Practice?

Now that you’ve got the basics, let’s dive into how the GC works. It operates in two main phases: identification and cleanup.

I’ll explain each one in a simple way.

1. Identification: Who Can Be Discarded?

The GC uses a concept called reachability. Basically, it checks which objects still have active references in your code.

If an object is no longer “reachable”—meaning no variable or structure points to it—it’s considered garbage and can be removed.

For example, picture this code:

public class Example {
public static void main(String[] args) {
String name = "John"; // Object in the heap
name = null; // No reference, "John" becomes garbage
}
}

When the variable name is set to null, the "John" object loses its reference. The GC notices this and marks it for cleanup. Simple, right?

2. Cleanup: Time to Free Up Space

After identifying what’s garbage, the GC swings into action to free up the memory.

It doesn’t do this all the time, though. The JVM decides the right moment based on smart algorithms, like memory usage or system needs.

That’s what we call a “collection cycle.”

And here’s more: the GC isn’t a one-size-fits-all process. It varies depending on the Java version and the collector you’re using. We’ll get to that in a bit.

The JVM’s Garbage Collectors: Meet the Main Ones

The JVM has several types of Garbage Collectors, each with its own characteristics.

I’ll show you the most common ones so you can figure out which might fit your project best.

CollectorDescriptionIdeal For
Serial GCRuns on a single thread, pausing the program during collection.Small applications or low-load scenarios.
Parallel GCUses multiple threads for collection, optimizing time.Systems needing high throughput.
G1 GCDivides the heap into regions and prioritizes areas with more garbage.Large applications with low latency needs.

The G1 GC, for instance, is the default in newer Java versions (starting with Java 9). It’s great for those who want a balance between performance and short pauses.

The Serial GC, on the other hand, is more basic, ideal for tests or simple projects.

The Heap and Its Generations: The GC’s Secret

Another key point is how the JVM organizes memory in the heap. It’s divided into “generations,” which helps the GC be more efficient.

They are:

  • Young Generation: Where new objects are born. Collection here is more frequent since many objects have short lifespans.
  • Old Generation: Where objects that survive longer go. Cleanup here is less frequent but heavier.
  • Permanent Generation: Used for metadata (in older versions, up to Java 7). Nowadays, this has been replaced by Metaspace.

This division is based on the idea that most objects die young.

So, the GC focuses on the Young Generation for quick cleanups, while leaving the Old Generation for rarer cycles.

Practical Examples: GC in Action

Enough theory—let’s see Garbage Collection in action!

I’ll show you a simple example and how to force the GC to understand its impact.

public class TestGC {
public static void main(String[] args) {
for (int i = 0; i < 10000; i++) {
String temp = new String("Object " + i); // Creating objects
}
System.out.println("Objects created!");
System.gc(); // Suggesting GC execution (not guaranteed)
System.out.println("GC suggested!");
}
}

In this code, we create 10,000 objects in a loop. Since the temp variable is reassigned each iteration, the previous objects lose their reference and become candidates for the GC.

The System.gc() method is just a suggestion—the JVM decides whether to run it or not.

If you run this with tools like VisualVM (available at visualvm.github.io), you can monitor memory and watch the GC clean the heap in real-time. It’s pretty cool for understanding its behavior!

Best Practices with Garbage Collection

Before wrapping up, let me give you some tips to make the most of the GC:

  1. Avoid creating unnecessary objects: Less garbage means less work for the GC.
  2. Nullify when possible: Setting references you no longer use to null helps the GC identify garbage.
  3. Choose the right collector: Tune the GC to your use case (e.g., use G1 for low latency).

Conclusion: Master the GC and Boost Your Code

So, did you enjoy the chat? Garbage Collection in Java is one of those topics that seems tricky, but once you understand how the JVM manages memory, it all becomes clearer.

With the examples I showed you, you can visualize how it works and even optimize your projects.

If you want to dive deeper, try playing with JVM flags (like -Xms and -Xmx) to configure the heap. But that’s a topic for another day. For now, test what you’ve learned and let me know how it goes!

Any questions, just holler. Ready to code smarter?

linkedinlinkedinlinkedin