🧹 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
- Objects are created on the heap
- Java checks which objects are still reachable (used or referenced)
- Unreachable objects are marked for collection
- 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)
- Mark – Identify reachable objects
- Sweep – Remove unreferenced objects
- 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)
✅ 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)
🧠 Output may include:
⚠️
finalize()
is deprecated since Java 9. UseCleaner
orPhantomReference
for cleanup tasks in modern code.
💡 2. SoftReference Example – survives until memory is low
🧠 It still prints the object unless JVM is low on memory.
💨 3. WeakReference Example – cleared in next GC cycle
🧠 Likely to print null
, because WeakReferences are collected eagerly.
🧟 4. PhantomReference Example – used for cleanup post-GC
🧠 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 |