Java.Core.What is the garbage collector for?

The Garbage Collector (GC) in Java is responsible for automatically managing memory by reclaiming objects that are no longer reachable. It helps prevent memory leaks and optimizes memory usage without requiring manual memory management (unlike C or C++).


1. Why Do We Need a Garbage Collector?

Automatic Memory Management – No need to manually free() memory.
Prevents Memory Leaks – Removes unused objects to free up space.
Improves Performance – Optimizes heap memory usage.
Avoids Manual Errors – Eliminates issues like dangling pointers.


2. How Does the Garbage Collector Work?

Java uses a heap memory where objects are stored. The garbage collector removes objects that are no longer reachable (i.e., no active references exist).

Garbage Collection Process

  1. Allocation: Objects are allocated in the heap (new keyword).
  2. Reachability Analysis: GC determines if an object is still referenced.
  3. Mark & Sweep:
    • Mark – Identify objects still in use.
    • Sweep – Remove unreachable objects.
  4. Memory Compaction (optional): Reorganizes memory for efficiency.

3. When Does Garbage Collection Occur?

Automatically by the JVM when memory is low.
Manually triggered using System.gc() (not guaranteed).
On object dereferencing, when no references point to an object.


4. Example: Garbage Collection in Action

Example 1: Objects Becoming Unreachable

class Example {
    String name;

    Example(String name) {
        this.name = name;
    }

    protected void finalize() {
        System.out.println(name + " is being garbage collected!");
    }

    public static void main(String[] args) {
        Example obj1 = new Example("Object 1");
        Example obj2 = new Example("Object 2");

        obj1 = null; // Eligible for garbage collection
        obj2 = null; // Eligible for garbage collection

        System.gc(); // Request for garbage collection (not guaranteed)
    }
}

Possible Output (GC timing varies):

Object 1 is being garbage collected!
Object 2 is being garbage collected!

🚀 Objects become unreachable when their references are removed, making them eligible for GC.


Example 2: Losing Reference to an Object

class Demo {
    int id;

    Demo(int id) {
        this.id = id;
    }

    public static void main(String[] args) {
        Demo obj = new Demo(1); // Object created
        obj = new Demo(2); // First object is now unreachable, eligible for GC

        System.gc(); // Requests GC (may not run immediately)
    }
}

🔹 The first Demo(1) object is no longer referenced, so it can be garbage collected.


5. Types of Garbage Collectors in Java

Java provides different GC algorithms:

Garbage CollectorDescriptionBest Used For
Serial GCUses a single thread, best for small applications.Single-threaded applications.
Parallel GCUses multiple threads for faster collection.Multi-threaded applications.
G1 (Garbage First) GCSplits the heap into regions for efficient cleaning.General-purpose, large heaps.
ZGC & Shenandoah GCLow-pause-time collectors for real-time applications.Low-latency applications.

🔹 Default GC: G1GC (Java 9+)


6. How to Request Garbage Collection?

Using System.gc()

System.gc(); // Requests garbage collection (not guaranteed)

Using Runtime.getRuntime().gc()

Runtime.getRuntime().gc();

🚫 However, both are just requests. The JVM decides when GC actually runs!


7. Finalization (finalize() method)

The finalize() method is called before an object is garbage collected, but it’s deprecated in Java 9+.

Example: Using finalize() (Deprecated)

class Demo {
    protected void finalize() {
        System.out.println("Object is being garbage collected!");
    }

    public static void main(String[] args) {
        Demo obj = new Demo();
        obj = null;
        System.gc(); // Triggers finalize() before collecting the object
    }
}

Output:

Object is being garbage collected!

🚨 finalize() is unreliable and should not be used.


8. How to Make an Object Eligible for GC?

An object becomes eligible for garbage collection when there are no more references to it.

Ways to Make an Object Eligible for GC

  1. Setting reference to null
MyClass obj = new MyClass();
obj = null; // Now eligible for GC

2. Reassigning a reference

MyClass obj = new MyClass();
obj = new MyClass(); // First object loses reference, becomes eligible for GC

3. Objects inside a method (go out of scope)

void method() {
    MyClass obj = new MyClass(); // Eligible for GC when method exits
}

4. Removing objects from a collection

List<MyClass> list = new ArrayList<>();
MyClass obj = new MyClass();
list.add(obj);
list.remove(obj); // Eligible for GC

9. Common Myths About Garbage Collection

MythReality
System.gc() immediately cleans up objects❌ It’s just a request, JVM decides when to run GC.
GC guarantees no memory leaks❌ Poorly managed static references and collections can still cause memory leaks.
GC makes programs slower❌ GC optimizes memory usage, and modern collectors are highly efficient.

10. Summary

FeatureDescription
PurposeAutomatically frees memory by collecting unused objects.
How it WorksUses reachability analysis (Mark & Sweep).
GC TriggerRuns automatically or via System.gc().
GC TypesSerial, Parallel, G1, ZGC, Shenandoah.
When Objects Are Collected?When no references exist.
Alternatives?Manual close() for external resources like files.
This entry was posted in Без рубрики. Bookmark the permalink.