Garbage Collection in Java Explained with Examples and GC Types

One of the biggest advantages of Java is automatic memory management. Unlike languages where developers are responsible for allocating and freeing memory manually, Java uses Garbage Collection to reclaim memory occupied by unused objects.


Garbage Collection is a favourite interview topic because it directly relates to JVM performance, memory management and application scalability.


What is Garbage Collection?

Garbage Collection is the process of automatically identifying and removing objects that are no longer being used by the application.

The Garbage Collector helps free Heap Memory by removing unreachable objects.


Example


Employee employee = new Employee();

employee = null;

After the reference becomes null, the Employee object becomes eligible for Garbage Collection.


Why Garbage Collection is Important

Without Garbage Collection, applications would continue consuming memory until the system eventually crashed.


Benefits include:

  • Automatic memory management
  • Reduced memory leaks
  • Improved developer productivity
  • Better application stability

Garbage Collection Terminologies

Reachable Object

An object that can still be accessed through an active reference.



Employee employee = new Employee();

The object is reachable because employee references it.


Unreachable Object

An object that no longer has any active references.



Employee employee = new Employee();

employee = null;

The object becomes unreachable and can be collected.


Object Lifecycle


Object Created
       |
       v
Object Used
       |
       v
Reference Removed
       |
       v
Eligible For GC
       |
       v
Memory Reclaimed

Heap Memory Structure

Garbage Collection primarily works inside Heap Memory.



Heap Memory
   |
   +-- Young Generation
   |
   +-- Old Generation

Different garbage collection strategies are applied to different regions of the heap.


Young Generation

Newly created objects are initially allocated in the Young Generation.

Most application objects are short-lived and are collected from this area quickly.


Components

  • Eden Space
  • Survivor Space S0
  • Survivor Space S1

Old Generation

Objects that survive multiple garbage collection cycles are promoted to the Old Generation.

These objects typically have a longer lifespan.


Minor Garbage Collection

Minor GC occurs when memory in the Young Generation becomes full.

Unused objects are removed and surviving objects are moved to Survivor spaces.

Minor GC is generally fast and frequent.


Major Garbage Collection

Major GC targets objects stored in the Old Generation.

This process is usually slower because it works on a significantly larger memory area.


Full Garbage Collection

Full GC cleans both Young Generation and Old Generation memory areas.

Full GC is the most expensive type of garbage collection and can temporarily impact application performance.


Using System.gc()

Java allows developers to request garbage collection.



System.gc();

However, this is only a request. The JVM may choose to ignore it.


Finalize Method

Historically, Java provided the finalize() method that could execute before object cleanup.



@Override
protected void finalize()
throws Throwable {

    System.out.println("Object removed");

}

Modern Java versions discourage using finalize() because of performance and reliability concerns.


Popular Garbage Collectors in Java

Serial GC

Uses a single thread for garbage collection. Suitable for small applications.


Parallel GC

Uses multiple threads and focuses on throughput.


CMS GC

Concurrent Mark Sweep reduces pause times but has largely been replaced by newer collectors.


G1 Garbage Collector

G1GC is the default garbage collector in modern Java versions.

It divides the heap into regions and prioritises efficient memory cleanup.


Z Garbage Collector (ZGC)

ZGC is designed for very large heaps and extremely low pause times.

It is frequently used in large-scale enterprise systems.


Example Program


public class GCDemo {

    public static void main(String[] args) {

        Employee emp =
                new Employee();

        emp = null;

        System.gc();

    }
}

The Employee object becomes eligible for garbage collection when the reference is removed.


Common Interview Questions

What is Garbage Collection?

Garbage Collection is the process of automatically reclaiming memory occupied by unused objects.


Can we force Garbage Collection?

No. We can request Garbage Collection using System.gc(), but the JVM decides whether to execute it.


What is the difference between Minor GC and Major GC?

Minor GC works on Young Generation. Major GC works on Old Generation.


Which Garbage Collector is the default in modern Java?

G1 Garbage Collector is the default collector in modern Java releases.


What makes an object eligible for Garbage Collection?

An object becomes eligible when no active references point to it.


Best Practices

  • Remove unnecessary object references.
  • Avoid creating excessive temporary objects.
  • Use object pooling carefully.
  • Monitor GC logs in production environments.
  • Choose an appropriate GC strategy for your workload.

Frequently Asked Questions (FAQ)

Does Garbage Collection immediately destroy objects?

No. An object becomes eligible for collection, but actual removal depends on JVM behaviour.



Can local variables be garbage collected?

No. Garbage Collection mainly operates on Heap Memory objects.


What is a memory leak in Java?

A memory leak occurs when objects remain referenced even though they are no longer needed.


Why is Full GC considered expensive?

Because it processes large portions of heap memory and can increase application pause times.


Conclusion

Garbage Collection is one of the most important JVM features. It simplifies memory management by automatically reclaiming unused memory and reducing the possibility of memory-related failures. Understanding object lifecycle, heap generations, Minor GC, Major GC, G1GC and ZGC is essential for Java developers and interview preparation.


Keywords

Garbage Collection in Java, Java Garbage Collector, G1GC Explained, ZGC Explained, Minor GC vs Major GC, Heap Memory Management, Java Memory Management, JVM Garbage Collection, Java Performance Tuning, GC Interview Questions, Java Heap Memory, Full GC Java, Object Lifecycle Java, Core Java Interview Questions, JVM Internals


Garbage Collection in Java Explained with Examples and GC Types Garbage Collection in Java Explained with Examples and GC Types Reviewed by 13thGhost on 3:01 AM Rating: 5

No comments:

Recommended Posts

Powered by Blogger.