Garbage Collection in Java with Example: A Complete Guide

Robert Jul 13, 2026

Garbage collection in Java is a critical process that automatically manages memory allocation and deallocation to prevent memory leaks and ensure efficient program execution. This article delves into the intricacies of garbage collection in Java, with practical examples.

Understanding Garbage Collection in java — Java2Blog
Understanding Garbage Collection in java — Java2Blog

Before proceeding, it's essential to understand that Java's automatic memory management means it doesn't rely on explicit commands like 'free' or 'delete,' as seen in languages such as C or C++. Instead, the Java Virtual Machine (JVM) utilizes a garbage collector to clean up objects that are no longer in use, freeing up memory.

Java Garbage Collection - Clean Java, Happy Java!
Java Garbage Collection - Clean Java, Happy Java!

The Garbage Collection Process in Java

The garbage collection process in Java involves three primary steps: marking, normal deletion, and scavenging. These steps ensure that objects that are no longer referenced by any part of the program are removed from memory.

Java 12 Garbage Collector Example - Java Code Geeks
Java 12 Garbage Collector Example - Java Code Geeks

The exact mechanism might differ based on the type of garbage collector used by the JVM. Different collectors include Serial GC, Parallel GC, CMS (Concurrent Mark Sweep) GC, and G1 ( Ĝab Athlete) GC, each characterized by how they perform the marking, sweeping, and compaction phases.

Marking Phase

Garbage Collection in Java - Scientech Easy
Garbage Collection in Java - Scientech Easy

In the marking phase, the garbage collector identifies which objects are still in use. It marks these objects as live, which are still referenced somewhere in the system, and unmarks those that are no longer needed.

For instance, consider the following scenario: ```java Object obj = new Object(); ... obj = null; // obj is now eligible for garbage collection ``` Once `obj` is set to `null`, it is marked for garbage collection in the next GC cycle.

Sweeping or Deletion Phase

Learn about an essential concept- Java Garbage Collection
Learn about an essential concept- Java Garbage Collection

After the marking phase, the garbage collector sweeps the memory, deleting all unmarked objects. This frees up memory, making it available for other objects.

As an example: ```java Object obj1 = new Object(); Object obj2 = new Object(); ... obj1 = null; ... // GC will delete obj1 and obj2, as obj2 is only referenced by obj1 which is null ``` In this case, both `obj1` and `obj2` are eligible for garbage collection.

Methods Triggering Garbage Collection in Java

An Ultimate Guides to Garbage Collection in Java
An Ultimate Guides to Garbage Collection in Java

The JVM determines when to run garbage collection based on various factors, such as available memory. However, you can also explicitly trigger garbage collection using several methods in the `Runtime` class.

Suède en are: ```java Runtime.getRuntime().gc(); // Request Java Virtual Machine (JVM) to run garbage collection Runtime.getRuntime().runFinalization(); // Run finalizers in the Java virtual machine (JVM). ``` These methods allow for manual control, although they're typically used for testing or debugging purposes only.

JVM tuning and garbage collection optimization
JVM tuning and garbage collection optimization
Code for Garbage Collection
Code for Garbage Collection
What Is JVM in Java? JVM Architecture Explained
What Is JVM in Java? JVM Architecture Explained
Recycling Photography, Plastic Recycling, Living Photo, Solid Waste, Recycled Projects, Eco Living, Waste Disposal, Plastic Waste, Social Media Design Graphics
Recycling Photography, Plastic Recycling, Living Photo, Solid Waste, Recycled Projects, Eco Living, Waste Disposal, Plastic Waste, Social Media Design Graphics
an image of trash cans labeled in different colors and sizes, with the words paper & card on each side
an image of trash cans labeled in different colors and sizes, with the words paper & card on each side
a collage of photos showing different types of waste in the grass and on top of it is a recyclable recycling bin
a collage of photos showing different types of waste in the grass and on top of it is a recyclable recycling bin
several trash cans are stacked on top of each other
several trash cans are stacked on top of each other
Waste Vectors - Download Free High-Quality Vectors | Magnific (formerly Freepik)
Waste Vectors - Download Free High-Quality Vectors | Magnific (formerly Freepik)
sore youtube waste - AI Art
sore youtube waste - AI Art
a poster with instructions to sorting recyclables and garbage in nagoya
a poster with instructions to sorting recyclables and garbage in nagoya
three trash cans labeled in different colors and sizes with the words waste separation on them
three trash cans labeled in different colors and sizes with the words waste separation on them
Waste Management (Citizens)
Waste Management (Citizens)
Recycle bin for waste separation outline set icon compostable general recycle and hazardous waste | Premium Vector
Recycle bin for waste separation outline set icon compostable general recycle and hazardous waste | Premium Vector
an image of a tower labeled in parts
an image of a tower labeled in parts
Waste Management:From Waste to Worth ♻️
Waste Management:From Waste to Worth ♻️
Plastic Culture in Japan: Challenges, Selective Sorting, and New Recycling Management Solutions
Plastic Culture in Japan: Challenges, Selective Sorting, and New Recycling Management Solutions
three colorful trash cans with different types of garbage flying out of them and around the bins
three colorful trash cans with different types of garbage flying out of them and around the bins
the flow diagram for waste generation and disposals, with different types of garbage in it
the flow diagram for waste generation and disposals, with different types of garbage in it
two workers in hardhats sorting trash on a conveyor belt
two workers in hardhats sorting trash on a conveyor belt
trash cans are lined up on the side of the street with bags and other garbage
trash cans are lined up on the side of the street with bags and other garbage

Examples of Object Eligibility for Garbage Collection

Understanding when an object is eligible for garbage collection is crucial. An object is eligible for GC when: - It's no longer referenced by any part of the program. - Its finalizer method has been executed, and no other objects refer to it. - It has not been marked as continuingly useful by the finalizer or any other method.

For example: ```java Object obj = new Object() { protected void finalize() throws Throwable { System.out.println("Object is being finalized"); } }; obj = null; // obj is now eligible for garbage collection ``` When `obj` is set to `null`, the JVM may still keep it alive until its `finalize` method runs. Once the `finalize` method executes, the object is eligible for garbage collection.

In conclusion, garbage collection in Java is a powerful feature ensuring efficient memory management. Understanding and leveraging it effectively can significantly enhance the performance of your Java applications.