🧹 Garbage Collection in Java

Java uses automatic garbage collection (GC) to manage memory.
The Garbage Collector frees memory by removing objects that are no longer reachable in your program.


🔁 How It Works

  1. Objects are created on the heap
  2. Java checks which objects are still reachable (used or referenced)
  3. Unreachable objects are marked for collection
  4. Garbage Collector reclaims the memory

🧠 GC runs in the background as a low-priority daemon thread.


🧱 Types of Objects (Based on Reachability)

Object Type Description
Reachable Accessible through a reference in the stack, static field, or another object
Softly Reachable Referenced only by SoftReference — cleared if memory is low
Weakly Reachable Referenced only by WeakReference — collected on next GC cycle
Phantom Reachable Referenced by PhantomReference, no longer usable, enqueued after GC
Unreachable No references — eligible for garbage collection

♻️ GC Phases (Typical Flow)

  1. Mark – Identify reachable objects
  2. Sweep – Remove unreferenced objects
  3. Compact – Rearrange memory to reduce fragmentation (optional)

🧠 Common Garbage Collectors

Collector Name Use Case / Target
Serial GC Single-threaded (small apps, client-side)
Parallel GC (Throughput GC) Multi-threaded (default for many apps)
G1 GC (Garbage First) Balanced for low pause + throughput
ZGC / Shenandoah Ultra-low latency (for very large heaps)

🧪 Forcing Garbage Collection (Not Recommended in Prod)

System.gc();  // Suggests JVM to run GC, not guaranteed

✅ Summary Table

Concept Meaning
Reachable Object is still used
Unreachable Eligible for garbage collection
Soft Reference GC only when memory is low
Weak Reference GC on next cycle
Phantom Reference GC done, used for cleanup before finalization
GC Trigger Automatic (or via System.gc() suggestion)

 

🧪 1. Finalization with finalize() (Deprecated but demonstrative)

class FinalizeDemo {
    @Override
    protected void finalize() throws Throwable {
        System.out.println("Finalize method called for: " + this);
    }

    public static void main(String[] args) {
        FinalizeDemo obj = new FinalizeDemo();
        obj = null;

        System.gc(); // Suggests garbage collection
        System.out.println("GC requested");
    }
}

🧠 Output may include:

GC requested
Finalize method called for: FinalizeDemo@xxxxxx

⚠️ finalize() is deprecated since Java 9. Use Cleaner or PhantomReference for cleanup tasks in modern code.


💡 2. SoftReference Example – survives until memory is low


import java.lang.ref.SoftReference;

public class SoftReferenceDemo {
    public static void main(String[] args) {
        String str = new String("CertifiKation");
        SoftReference<String> softRef = new SoftReference<>(str);

        str = null; // Clear strong reference
        System.gc();

        System.out.println("SoftReference still holds: " + softRef.get());
    }
}

🧠 It still prints the object unless JVM is low on memory.


💨 3. WeakReference Example – cleared in next GC cycle

import java.lang.ref.WeakReference;

public class WeakReferenceDemo {
    public static void main(String[] args) {
        String str = new String("WeakCertifiKation");
        WeakReference<String> weakRef = new WeakReference<>(str);

        str = null; // Remove strong reference
        System.gc();

        System.out.println("WeakReference now holds: " + weakRef.get());
    }
}

🧠 Likely to print null, because WeakReferences are collected eagerly.


🧟 4. PhantomReference Example – used for cleanup post-GC

import java.lang.ref.*;

public class PhantomReferenceDemo {
    public static void main(String[] args) throws InterruptedException {
        ReferenceQueue<String> queue = new ReferenceQueue<>();
        PhantomReference<String> phantomRef = new PhantomReference<>(new String("PhantomData"), queue);

        System.gc(); // Suggest GC

        Thread.sleep(1000); // Give GC time

        if (phantomRef.isEnqueued()) {
            System.out.println("PhantomReference enqueued for cleanup.");
        } else {
            System.out.println("PhantomReference not yet enqueued.");
        }
    }
}

🧠 Used for resource cleanup without exposing the actual object.


✅ Summary

Reference Type Cleared When Purpose
Strong Reference Never (unless set to null) Default reference
SoftReference On memory pressure Caching
WeakReference On next GC cycle Weak maps, canonicalization
PhantomReference After GC, before final cleanup Post-mortem cleanup, resource mgmt
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.