🔹 Garbage Collection in OOP

**Garbage Collection (GC)** is an automatic memory management process in Object-Oriented Programming (OOP) that **reclaims unused memory** occupied by objects that are no longer needed. This helps in **preventing memory leaks** and optimizing system performance.

📌 Why Use Garbage Collection?

Garbage Collection **automatically manages memory**, ensuring efficient resource utilization.

  • ✅ **Prevents Memory Leaks** – Removes unused objects from memory.
  • ✅ **Improves Performance** – Frees up memory for other processes.
  • ✅ **Reduces Manual Memory Management** – No need to manually delete objects.
  • ✅ **Enhances Program Stability** – Avoids crashes due to excessive memory usage.

📌 How Garbage Collection Works

Most modern programming languages use **automatic garbage collectors** to manage memory.

  • 1️⃣ **Object Allocation** – When an object is created, memory is allocated to it.
  • 2️⃣ **Object Becomes Unreachable** – If no references point to an object, it becomes garbage.
  • 3️⃣ **Garbage Collector Identifies Unused Objects** – GC detects objects that are no longer referenced.
  • 4️⃣ **Memory is Freed** – GC removes unused objects and reclaims memory.

🖥️ Garbage Collection in Java

Java uses the **JVM Garbage Collector** to free memory automatically.


            class GarbageExample {
                protected void finalize() {
                    System.out.println("Garbage Collected!");
                }
            
                public static void main(String[] args) {
                    GarbageExample obj1 = new GarbageExample();
                    GarbageExample obj2 = new GarbageExample();
            
                    obj1 = null;  // No longer referenced
                    obj2 = null;  // No longer referenced
            
                    System.gc();  // Suggests JVM to run Garbage Collector
                }
            }
                

🖥️ Garbage Collection in Python

Python uses **reference counting** and **cycle detection** for memory management.


            import gc
            
            class Test:
                def __del__(self):
                    print("Garbage Collected!")
            
            obj = Test()
            del obj  # Deletes object
            gc.collect()  # Forces garbage collection
                

📌 Types of Garbage Collection

  • Reference Counting: An object is deleted when no references point to it.
  • Mark-and-Sweep: GC marks active objects and removes unreferenced ones.
  • Generational GC: Objects are categorized into **young, old, and permanent** generations for efficient collection.

📌 Best Practices for Efficient Memory Management

  • ✅ Set unused object references to null to make them eligible for garbage collection.
  • ✅ Avoid memory leaks by closing database connections and file streams.
  • ✅ Use **weak references** for caching temporary data.
  • ✅ Optimize **data structures** to minimize unnecessary object creation.

🎯 Summary

Garbage Collection **automates memory management**, ensuring efficient memory usage and program stability. Java, Python, and other languages use different techniques like **reference counting** and **generational collection**.

🔗 Next Topics