SrcForge

Lesson 60

Garbage Collection

Garbage Collection in Java is the automatic process of removing objects that are no longer being used by the program. It helps the Java Virtual Machine (JVM) free heap memory by destroying unreferenced objects, which improves memory management and reduces manual cleanup work.

Java Track

Save progress as you learn.

61 lessons

Lesson content

Garbage Collection in Java is the automatic process of removing objects that are no longer being used by the program. It helps the Java Virtual Machine (JVM) free heap memory by destroying unreferenced objects, which improves memory management and reduces manual cleanup work.

What is Garbage Collection in Java?

In Java, garbage means objects that are no longer referenced by the program. Garbage collection is the process of identifying and removing those unreferenced objects from memory. Java performs this process automatically through the JVM Garbage Collector.

In simple words: if an object is created in heap memory but no variable points to it anymore, that object becomes eligible for garbage collection.

Key Terms

  • Garbage: Unreferenced objects that are no longer used by the program.
  • Garbage Collection: The automatic process of removing unused objects from heap memory.
  • Unreferenced object: An object that no active reference variable points to.
  • JVM: Java Virtual Machine, which manages memory and runs Java programs.
  • finalize(): A method that was traditionally called before an object was removed by the garbage collector.
  • gc(): A method used to request the JVM to run garbage collection.

Why Garbage Collection is Important in Java

Garbage collection is important because Java creates many objects during program execution. If unused objects are not removed, heap memory can fill up quickly.

Benefits of Garbage Collection

  • Automatically manages memory
  • Removes unused objects
  • Reduces memory leaks caused by forgotten cleanup
  • Improves application stability
  • Helps optimize heap memory usage

How Garbage Collection Works

When Java programs run, objects are created in heap memory. Over time, some of these objects are no longer needed. The garbage collector checks for objects that are not reachable through any live reference. These objects become eligible for removal.

Basic Flow

  • Object is created in heap memory
  • Reference to the object is lost or removed
  • Object becomes eligible for garbage collection
  • JVM may remove the object and reclaim memory

When Does an Object Become Eligible for Garbage Collection?

An object becomes eligible for garbage collection when it is no longer referenced by any live part of the program.

Common Cases

1. Reference is Set to null

obj = null;

2. One Object Reference is Reassigned to Another Object

obj1 = obj2;

The old object referenced by obj1 may become unreachable.

3. Local Object Goes Out of Scope

If an object is created inside a method and no reference exists after the method ends, it becomes eligible for garbage collection.

4. Anonymous Objects

Objects created without storing a reference can quickly become eligible for garbage collection.

Java gc() Method

Java provides the gc() method to request garbage collection.

Common Ways to Call It

System.gc();

// or

Runtime.getRuntime().gc();

Important note: gc() does not guarantee that garbage collection will run immediately. It only requests the JVM to perform garbage collection.

Java finalize() Method

The finalize() method is called a finalizer. It was traditionally used to perform cleanup work before an object is removed from memory.

Main Purpose of finalize()

  • Release resources used by the object
  • Perform cleanup before destruction
  • Act as a safety mechanism if cleanup was not done elsewhere

Important modern note: in modern Java, finalize() is deprecated and should generally be avoided in new code. It is still useful to understand for legacy Java tutorials and older projects.

Example 01: Simple Garbage Collection Example

This example creates two objects, removes their references, and requests garbage collection.

package GarbageCollection;

public class ex1 {

	public void finalize() {
		System.out.println("Object in the  garbage collection");
	}
	
	public static void main(String[] args) {
		
			ex1 ex = new ex1();
			ex1 exobj = new ex1();
			
			ex=null;
			exobj=null;
			
			System.gc();

	}
	
}

Explanation of Example 01

  • Step 1: Two objects of class ex1 are created.
  • Step 2: Both references are set to null (ex = null; exobj = null;). Now both objects are no longer referenced.
  • Step 3: System.gc() requests the JVM to run garbage collection.
  • Step 4: If the JVM decides to collect those objects, the finalize() method may run and print: Object in the garbage collection

Example 02: Garbage Collection with Reference Reassignment

This example shows how an object becomes eligible for garbage collection when references are reassigned.

package GarbageCollection;

public class GarbageCollectionExample {

    public static void main(String[] args) {

        GarbageCollectionExample obj1 = new GarbageCollectionExample();
        GarbageCollectionExample obj2 = new GarbageCollectionExample();

        // Assigning obj2 reference to obj1, making obj1 reference eligible for garbage collection
        obj1 = obj2;

        // Making obj2 reference null, making obj2 eligible for garbage collection
        obj2 = null;

        // Requesting garbage collection explicitly
        System.gc();

        // Printing a message to indicate that the objects have been garbage collected
        System.out.println("Garbage collection has been requested.");

        // Adding a delay to observe the garbage collection process
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // Overriding the finalize() method to print a message when the object is being garbage collected
    @Override
    protected void finalize() throws Throwable {
        System.out.println("Object is being garbage collected: " + this);
    }
}

Explanation of Example 02

  • Initially: Two objects are created — obj1 and obj2.
  • Then: obj1 = obj2; changes the reference. Now the original object referenced by obj1 has no reference and becomes eligible for garbage collection.
  • Next: obj2 = null; makes obj2 null. Now only one object may remain referenced, depending on how references are shared.
  • Finally: System.gc() requests the JVM to perform garbage collection.

Important Points About Garbage Collection in Java

1. Garbage Collection Works Mainly on Heap Memory

Objects are stored in heap memory, so garbage collection removes unused objects from the heap.

2. It is Automatic

The JVM manages garbage collection automatically. Programmers do not manually free object memory like in C or C++.

3. System.gc() is Only a Request

Calling System.gc() does not force immediate garbage collection.

4. Unreferenced Objects are Eligible, Not Guaranteed to be Removed Instantly

Eligibility does not mean immediate deletion.

5. finalize() is Not Reliable for Important Cleanup

Modern Java recommends other cleanup approaches such as try-with-resources for external resources.

finalize() vs gc()

Featurefinalize()gc()
TypeMethod in Object classMethod in System / Runtime
PurposeCleanup before object removalRequest JVM to run garbage collector
Called byJVM before object cleanupProgrammer or JVM
GuaranteeNo guarantee of execution timingNo guarantee GC will run immediately
Modern usageDeprecated / discouragedRarely needed in normal code

Advantages of Garbage Collection in Java

Automatic Memory Management

The programmer does not need to manually deallocate object memory.

Reduces Memory-Related Bugs

Helps avoid many common memory issues caused by forgotten cleanup.

Better Productivity

Developers can focus more on business logic than low-level memory handling.

Improves Application Stability

Unused objects are cleaned up when possible, helping the JVM reuse memory.

Best Practices for Java Garbage Collection

  • Do not rely on finalize() — it is deprecated and should not be used for critical cleanup in new applications.
  • Remove unnecessary object references — if objects are no longer needed, avoid keeping references to them.
  • Use try-with-resources for files, streams, and database connections — garbage collection manages memory, but it does not replace proper resource management.
  • Avoid creating too many unnecessary objects — too many short-lived objects can increase garbage collection work.
  • Understand object reachability — an object is eligible for garbage collection only when it is unreachable from active references.

FAQ

1. What is garbage collection in Java?

Garbage collection is the automatic JVM process of removing unreferenced objects from heap memory.

2. Does System.gc() force garbage collection?

No. System.gc() only requests garbage collection. The JVM decides whether and when to run it.

3. What is the purpose of finalize() in Java?

finalize() was used to run cleanup code before an object is removed, but it is now deprecated and not recommended for new code.

Garbage collection is the automatic JVM process of removing unreferenced objects from heap memory.
An object becomes eligible for garbage collection when no live reference points to it.
System.gc() only requests garbage collection; it does not guarantee immediate execution.
finalize() was traditionally used for cleanup before object removal but is now deprecated.
Common causes of eligibility include setting references to null, reassigning references, and objects going out of scope.
Best practice favors try-with-resources over finalize() for managing external resources like files and connections.

Where Java is used

Java in real-world development

Garbage Collection

Automatic JVM process that identifies and removes unreferenced objects from heap memory.

Unreferenced Object

An object with no active reference variable pointing to it, making it eligible for garbage collection.

System.gc()

Method used to request the JVM to run garbage collection, without guaranteeing immediate execution.

finalize()

Deprecated method traditionally called before an object's removal to perform cleanup work.

Object Eligibility

An object becomes eligible for garbage collection when it is no longer reachable from any live reference.

try-with-resources

Modern resource management approach recommended over finalize() for files, streams, and database connections.

Prev: Stack Memory vs Heap MemoryBack to hub